8

我有下面的 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>
';

这是我当前的代码DOMDocument

$dom = new DOMDocument;
$dom->loadHTML($string);
foreach( $dom->getElementsByTagName('a') as $node)
{
    $array[] = $node->nodeValue; 
}

print_r($array);

但是,这给出了以下输出:

Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 4)

但我正在寻找这个结果:

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>
)

这可能吗?

4

1 回答 1

26

将节点传递给以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);

结果:

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>
)

顺便说一句,仅适用于 PHP 5.3.6 及更高版本。

于 2012-04-28T18:45:49.800 回答