简体   繁体   中英

php DOMXpath query on DOMElement not working correctly

I'm trying to run an xpath query to return all elements inside < div class="classB"> with the key_id attribute set.

<?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'));
}
?>

which outputs the following:

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

but I'm trying to get this:

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

As you can see, I'm passing the "classB" div as a relative query:

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

My understanding is that query takes an optional domContext of type DOMNode, and $classB is a DOMElement which extends DOMNode.

What am I doing wrong?

Try

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

See demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM