<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
<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]