Php XPATH获取当前节点的属性

Php XPATH获取当前节点的属性,php,xpath,Php,Xpath,在PHP中获取当前节点的属性并基于该属性生成条件时遇到问题 示例XML <div class='parent'> <div class='title'>A Title</div> <div class='child'>some text</div> <div class='child'>some text</div> <div class='title'>A Title

在PHP中获取当前节点的属性并基于该属性生成条件时遇到问题

示例XML

<div class='parent'>
    <div class='title'>A Title</div>
    <div class='child'>some text</div>
    <div class='child'>some text</div>
    <div class='title'>A Title</div>
    <div class='child'>some text</div>
    <div class='child'>some text</div>
</div>
我已经试过了所有的方法,比如下面的

if ($xpath->query("./[@class='title']/text()",$node)->length > 0) { }

但我一直得到的是PHP错误,说我的XPATH语法无效。有人能帮我吗?

$node->getAttribute('class')
提供属性值,
$node->textContent
提供节点的字符串内容。我不会深入XPath来读取字符串值。

您可以在不同的节点列表中过滤“title”和“child”集合:

$titles   = $xpath->query("//div[@class='parent']/div[@class='title']");
$children = $xpath->query("//div[@class='parent']/div[@class='child']");
然后分别进行处理:

foreach ($titles as $title) {
   echo $title->textContent."\n";
}

foreach ($children as $child) {
   echo $child->textContent."\n";
}

请参阅:

您可以通过使用
getAttribute()
方法来实现这一点。例如:

foreach($nodeLIST as $node) {
    $attribute = $node->getAttribute('class');
    if($attribute == 'title') {
        // do something
    } elseif ($attribute == 'child') {
        // do something
    }
}

完美的工作起来很有魅力。。。我可以问一下,如果我在你的回答中遇到了elseif条件,并且该节点还有更多嵌套的DIV节点,为什么$xpath->query(“./DIV“,$node)不给我一个所有这些嵌套节点的数组呢?如果你想要嵌套的DIV,那么xpath必须是
//DIV
。嗨,是的。//DIV将给我所有嵌套的DIV节点,不管它们有多深,而./div将从当前节点获取一层深的嵌套div。我已经设法找到了$xpath->query(“./div”,$node)不起作用的原因-我正在读取的标记没有嵌套的div。。。谢谢你的帮助!感谢您的响应,但是我需要按顺序读取节点,并且有两个单独的循环对我来说效率很低…公平点,但是我读取节点的顺序很重要,因此在读取子节点之前知道标题节点的文本意味着我可以设置标题变量
foreach($nodeLIST as $node) {
    $attribute = $node->getAttribute('class');
    if($attribute == 'title') {
        // do something
    } elseif ($attribute == 'child') {
        // do something
    }
}