Nico Martin Nico Martin - 1 year ago 127
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
<li id="3">Sub Hallo</li>
<li id="4">Sub Welt</li>
$dom = new DOMDocument;

now I want to have all
IDs inside one array.

I tried the following:

$all_li_ids = array();
$menu_nodes = $dom->getElementById('mainmenu')->childNodes;
foreach($menu_nodes as $li_node){

As you might see, this will print out

How do I get all children (the subchildren as well

Answer Source

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){
print_r($all_li_ids); 1,2,3,4
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download