基本上你的
XPath
查询错误。我会这样使用DOM扩展:
$xml = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
EOF;
$doc = new DOMDocument();
$doc->loadXML($xml);
$selector = new DOMXPath($doc);
$result = $selector->query('//*');
foreach($result as $node) {
echo $node->nodeName . PHP_EOL;
}
输出:
note
to
from
heading
body
还有一种方法可以在没有
getName()
函数,因为标记名是
SimpleXmlElement
对象您需要编写一个递归解析器(我已经用迭代替换了递归以提高性能):
$xml = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<note>
<address>
<to>Tove</to>
<from>Jani<a>dsf</a></from>
</address>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
EOF;
$xml = simplexml_load_string($xml);
$stack = array($xml);
do {
$el = array_pop($stack);
foreach($el as $key => $val) {
if(gettype($val) !== 'string') {
$stack []= $val;
}
echo $key . PHP_EOL;
}
} while (!empty($stack));
Btw,PHP
5.0.5
很老了。难以置信你/他们还在使用它。
使现代化
然而,上面的代码应该适用于该版本的PHP。