nextSibling doesn't work when working with PHP DOMDocument

Viewed 4438

I tried to get a following element using nextSibling and the following code doesn't work. i've got an error as below PHP Warning: Invalid argument supplied for foreach() in /php/dom.php on line 35

that must be caused by the null value in the foreach loop.

but if I modify it to get the previous element using previousSibling it works as expected.

$doc = new DOMDocument();
$html = <<<HTML
<html>
<body>
<ul id="list">
<li>Foo</li>
<li>Bar</li>
</ul>
<h2 class = 'test'>heading2</h2>
<ul id="list2">
<li>list1</li>
<li>list2</li>
</ul>
</body>
</html>
HTML;

$doc ->loadHTML($html);

$DOMNodelist = $doc->getElementsByTagName('*');

foreach($DOMNodelist as $node) {
    if ($node -> hasAttribute('class')) {    
        foreach($node -> nextSibling ->childNodes as $morenodes) {
           print_r($morenodes);
       }
    }
}
2 Answers
Related