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