选择PHP DOM中所选节点的下一个节点? [英] Select the next node of the selected node in PHP DOM?

查看:110
本文介绍了选择PHP DOM中所选节点的下一个节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我正在开发一个这样的HTML文件

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>

我想选择其名称等于node的每个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;

但我只是收到错误


致命错误:调用未定义的方法DOMElement :: next_sibling()

Fatal error: Call to undefined method DOMElement::next_sibling()

有人可以告诉我有什么问题吗我的脚本吗?

Can anybody tell me what's wrong with my script please?

推荐答案

错误很清楚:没有方法 DOMElement :: next_sibling )。阅读 DOMElement的文档 ,它是父类 DOMNode 。您正在考虑属性 DOMNode :: nextSibling

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.

但是,code> nextSibling 获取下一个节点,而不是下一个元素。 (没有获取下一个元素的DOM方法或属性,您需要继续使用 nextSibling 并检查 nodeType 直到你打了另一个元素。)你的问题说你想要下一个节点,但我想你可能实际上想要下一个元素(空的< div> )。这实际上与XPath相当容易,为什么不这样做呢?

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?

立即获取:

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

如果您已经有一个< div name =节点>

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

这篇关于选择PHP DOM中所选节点的下一个节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆