使用DomDocument获取标签的位置


PHP - get position of tag with DomDocument

<a>
    <b id="bye">
        <name>john</name>
    </b>
    <b id="goodbye">
        <name>emma</name>
    </b>
</a>
使用该XML文件,我想打印如下内容:
b with id:bye has position 0
b with id:goodbye has position 1

可以使用Dom的XPath来获取所需的内容(更新后的输出与原始文章更匹配)。

<?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";
}

应该为您提供:

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