Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nextSibling doesn't work when working with PHP DOMDocument

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);
       }
    }
}
like image 579
JIA Avatar asked Dec 25 '22 15:12

JIA


1 Answers

Because your document has whitespace separating the elements, you'd actually need to use:
nextSibling->nextSibling
Or, the way I'd do it, because you already have a list generated from '*' for all the elements, I'd write it as:

foreach($DOMNodelist as $i=>$node) {
    if ($node -> hasAttribute('class')) {
        foreach($DOMNodelist->item($i+1)->childNodes as $morenodes) {
           print_r($morenodes);
       }
    }
}

Or you can just remove the whitespace from the document:

$html = <<<HTML
<html><body><ul id="list"><li>Foo</li><li>Bar</li></ul><h2 class = 'test'>heading3</h2><h3>heading3</h3><ul id="list2"><li>list2</li><li>list2</li></ul></body></html>
HTML;
like image 87
Ultimater Avatar answered Apr 28 '23 01:04

Ultimater