4

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

Breeze
  • 2,010
  • 2
  • 32
  • 43
Nico Martin
  • 1,268
  • 1
  • 14
  • 23

2 Answers2

2

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
splash58
  • 26,043
  • 3
  • 22
  • 34
1

One way to do it would be to add another foreach loop, ie:

foreach($menu_nodes as $node){
    if($node->nodeName=='li'){
        $all_li_ids[]=$node->getAttribute('id');         
    }
    foreach($node as $sub_node){
        if($sub_node->nodeName=='li'){
            $all_li_ids[]=$sub_node->getAttribute('id');         
        }
    }
}
Lee
  • 118
  • 11