So far I’m working on a HTML file like this
<div name="node"></div>
<div></div>
<div name="node"></div>
<div></div>
<div name="node"></div>
<div></div>
I want to select the next node of every “div” which has its name equal to “node” and I try :
$dom = new DOMdocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$els = $xpath->query("//div[@name='node']");
$j = 0;
foreach($els as $el)
{
if($el->next_sibling()) $j++;
}
echo $j;
But I just get an error
Fatal error: Call to undefined method DOMElement::next_sibling()
Can anybody tell me what’s wrong with my script please?
The error is quite clear: there is no method
DOMElement::next_sibling(). Read the documentation forDOMElementand it’s parent classDOMNode. You are thinking of the propertyDOMNode::nextSibling.However,
nextSiblinggets the next node, not the next element. (There is no DOM method or property that gets the next element. You need to keep usingnextSiblingand checkingnodeTypeuntil you hit another element.) Your question says you want the next node but I think you may actually want the next element (the empty<div>). This is actually quite easy to do with XPath, so why don’t you do that instead?To get it immediately:
To get it when you already have a
<div name="node">: