Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the next node of the selected node in PHP DOM?

Tags:

dom

php

xpath

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?

like image 337
Teiv Avatar asked Mar 03 '12 19:03

Teiv


3 Answers

I don't know php but this xpath gets them:

//div[@name="node"]/following-sibling::*[1]
like image 126
Birei Avatar answered Oct 13 '22 02:10

Birei


The error is quite clear: there is no method DOMElement::next_sibling(). Read the documentation for DOMElement and it's parent class DOMNode. You are thinking of the property DOMNode::nextSibling.

However, nextSibling gets the next node, not the next element. (There is no DOM method or property that gets the next element. You need to keep using nextSibling and checking nodeType until 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:

$els = $xpath->query("//div[@name='node']/following-sibling::*[1]");

To get it when you already have a <div name="node">:

$nextelement = $xpath->query("following-sibling::*[1]", $currentdiv);
like image 24
Francis Avila Avatar answered Oct 13 '22 00:10

Francis Avila


There's is not function called next_sibling() in DOM. You should use the property nextSibling defined in DOMNode (http://www.php.net/manual/en/class.domnode.php).

foreach($els as $el)
{
    if($el->nextSibling) $j++;
}
like image 41
Alexandre D'Eschambeault Avatar answered Oct 13 '22 00:10

Alexandre D'Eschambeault