PHP DOM:将 HTML 列表解析为数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10366458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP DOM: parsing a HTML list into an array?
提问by laukok
I have the below HTML string, and I would like to turn it into an array.
我有下面的 HTML 字符串,我想把它变成一个数组。
$string = '
<a href="#" class="something">1</a>
<a href="#" class="something">2</a>
<a href="#" class="something">3</a>
<a href="#" class="something">4</a>
';
Here's my current code with DOMDocument:
这是我当前的代码DOMDocument:
$dom = new DOMDocument;
$dom->loadHTML($string);
foreach( $dom->getElementsByTagName('a') as $node)
{
$array[] = $node->nodeValue;
}
print_r($array);
However, this gives the below output:
但是,这给出了以下输出:
Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 4)
But I am looking for this result:
但我正在寻找这个结果:
Array (
[0] => <a href="#" class="something">1</a>
[1] => <a href="#" class="something">2</a>
[2] => <a href="#" class="something">3</a>
[3] => <a href="#" class="something">4</a>
)
Is this possible?
这可能吗?
回答by Ry-
Pass the node to DOMDocument::saveHTMLto get its HTML representation:
将节点传递给以DOMDocument::saveHTML获取其 HTML 表示:
$string = '
<a href="#" class="something">1</a>
<a href="#" class="something">2</a>
<a href="#" class="something">3</a>
<a href="#" class="something">4</a>
';
$dom = new DOMDocument;
$dom->loadHTML($string);
foreach($dom->getElementsByTagName('a') as $node)
{
$array[] = $dom->saveHTML($node);
}
print_r($array);
Result:
结果:
Array
(
[0] => <a href="#" class="something">1</a>
[1] => <a href="#" class="something">2</a>
[2] => <a href="#" class="something">3</a>
[3] => <a href="#" class="something">4</a>
)
Only works with PHP 5.3.6 and higher, by the way.
顺便说一下,仅适用于 PHP 5.3.6 及更高版本。

