Nico Martin Nico Martin - 4 months ago 13
PHP Question

How to get all child nodes from DOMDocument?

I have the following

$string = '<html><head></head><body><ul id="mainmenu">
<li id="1">Hallo</li>
<li id="2">Welt
<ul>
<li id="3">Sub Hallo</li>
<li id="4">Sub Welt</li>
</ul>
</li>
</ul></body></html>';
$dom = new DOMDocument;
$dom->loadHTML($string);


now I want to have all
li
IDs inside one array.

I tried the following:

$all_li_ids = array();
$menu_nodes = $dom->getElementById('mainmenu')->childNodes;
foreach($menu_nodes as $li_node){
if($li_node->nodeName=='li'){
$all_li_ids[]=$li_node->getAttribute('id');
}
}
print_r($all_li_ids);


As you might see, this will print out
[1,2]


How do I get all children (the subchildren as well
[1,2,3,4]
)?

Answer

My test doesn't return element by using $dom->getElementById('mainmenu'). But if your using does, do not use Xpath

$xpath = new DOMXPath($dom);
$ul = $xpath->query("//*[@id='mainmenu']")->item(0);

$all_li_ids = array();
// Find all inner li tags
$menu_nodes = $ul->getElementsByTagName('li');
foreach($menu_nodes as $li_node){
        $all_li_ids[]=$li_node->getAttribute('id');         
}
print_r($all_li_ids); 1,2,3,4
Comments