简体   繁体   中英

PHP - get position of tag with DomDocument

<a>
    <b id="bye">
        <name>john</name>
    </b>
    <b id="goodbye">
        <name>emma</name>
    </b>
</a>

Using that XML file, I want to print something like:

b with id:bye has position 0
b with id:goodbye has position 1

You can use the Dom's XPath to get what you need ( updated to output a better match to original post ).

<?php

$xml = '<a>
    <b id="bye">
        <name>john</name>
    </b>
    <b id="goodbye">
    <name>emma</name>
    </b>
</a>';


$dom = new DOMDocument();
$dom->loadXML($xml);

foreach ( $dom->getElementsByTagName("b") as $domNode ) {
    print "b with id:{$domNode->attributes->getNamedItem("id")->nodeValue} has position {$domNode->getNodePath()}\n";
}

Should provide you with:

b with id:bye has position /a/b[1]
b with id:goodbye has position /a/b[2]

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