PHP - 使用DomDocument获取标记的位置

时间:2013-03-13 11:02:39

标签: php 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

1 个答案:

答案 0 :(得分:2)

你可以使用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]