在DOMElement上的php DOMXpath查询无法正常工作

时间:2014-03-03 16:56:34

标签: php xpath domdocument

我正在尝试运行xpath查询以返回<内部的所有元素div class =“classB”>设置key_id属性。

<?php
$dom = new DOMDocument;
$dom->loadHTML('
    <html>
    <head></head>
    <body>
        <div class="classA">
            <div key_id="a:1234"></div>
            <div key_id="a:2345"></div>
            <div key_id="a:3456"></div>
            <div class="sub"></div>
            <div class="sub"></div>
        </div>
        <div class="classB">
            <div key_id="b:1234"></div>
            <div key_id="b:2345"></div>
            <div key_id="b:3456"></div>
            <div class="sub"></div>
            <div class="sub"></div>
        </div>
    </body>
    </html>
    ');
$xpath = new DOMXpath ($dom);
$classB = $xpath->query("//*[contains(concat(' ', @class, ' '), ' classB ')]")->item(0);
$subNodes = $xpath->query("//*[@key_id]", $classB);
foreach($subNodes as $elem) {
    var_dump($elem->getAttribute('key_id'));
}
?>

输出以下内容:

string(6) "a:1234"
string(6) "a:2345"
string(6) "a:3456"
string(6) "b:1234"
string(6) "b:2345"
string(6) "b:3456"

但我想弄明白:

string(6) "b:1234"
string(6) "b:2345"
string(6) "b:3456"

如您所见,我将“classB”div作为相对查询传递:

$subNodes = $xpath->query("//*[@key_id]", $classB);

我的理解是查询采用DOMNode类型的可选domContext,而$ classB是扩展DOMNode的DOMElement。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试

$xpath = new DOMXpath ($dom);
$subNodes = $xpath->query("*/div[@class='classB']/div[@key_id]");
foreach($subNodes as $elem) {
    echo $elem->getAttribute('key_id');
}

请参阅演示here