PHP DOM: parsing a HTML list into an array?

北城以北 提交于 2019-11-29 00:18:27

Pass the node to DOMDocument::saveHTML to get its HTML representation:

$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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!