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);
}
}
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With