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

I'm still working on an 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 each "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 the error message

Fatal error: method call undefined DOMElement :: next_sibling ()

Can someone tell me what happened to my script, please?

+5
source share
4 answers

The error is pretty clear: DOMElement::next_sibling()there is no method . Read the documentation forDOMElement and the parent class DOMNode. You are thinking about a property DOMNode::nextSibling.

nextSibling node, . ( DOM, . nextSibling nodeType, .) , node, , ( <div>). XPath, ?

:

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

, <div name="node">:

$nextelement = $xpath->query("following-sibling::*[1]", $currentdiv);
+15

DOM , next_sibling(). nextSibling, DOMNode (http://www.php.net/manual/en/class.domnode.php).

foreach($els as $el)
{
    if($el->nextSibling) $j++;
}
+5

php, xpath :

//div[@name="node"]/following-sibling::*[1]
+4

(, )

foreach($els as $el){
  $next = $el->nextSibling;
  while($next){
    if($next->nodeType!==3){
       $j++;
       break;
    }
    $next = $next->nextSibling;
  }
}

function nextElement($node, $name=null){
    if(!$node){
        return null;
    }
    $next = $node->nextSibling;
    if(!$next){
        return null;
    }
    if($next->nodeType === 3){
        return self::nextElement($next, $name);
    }
    if($name && $next->nodeName !== $name){
        return null;
    }
    return $next;
}

foreach($els as $el)
{
    if(nextElement($el,'div')) $j++;
}
0

All Articles