使用PHP迭代DOM文档

时间:2014-09-05 23:32:01

标签: php xml domdocument

我只是试图通过迭代来获取PHP中XML文件的所有节点名称。这是我的尝试:

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML("<?xml version='1.0' encoding='ISO-8859-1'?><user><name>Michael Taylor</name><offers>0</offers><address><street>Ringstreet 8</street><zip>1100</zip><city>Norther</city></address><credit>473.43</credit></user>");
$node = $doc->firstChild;

function iterateXML($node) {
    if($node->childNodes->length == 0) {
        echo $node->nodeName;
        return;
    }
    $children = $node->childNodes;
    foreach($children as $child) {
        iterateXML($child);
    }
}
iterateXML($node);

然而,输出是

#text#text#text#text#text#text 

我做错了什么?

编辑:

我的最终计划是将子项的名称添加到由“_”分隔的父节点的名称,因此上面示例的最终输出应为:

name
offers
address_street
address_zip
address_city
credit

最简单的方法是什么?

1 个答案:

答案 0 :(得分:2)

不仅元素是节点。您输出没有子节点的节点的名称。在您的XML中仅为文本节点。

您可以检查节点类型...或使用XPath:

$xml = <<<'XML'
<?xml version='1.0' encoding='ISO-8859-1'?><user><name>Michael Taylor</name><offers>0</offers><address><street>Ringstreet 8</street><zip>1100</zip><city>Norther</city></address><credit>473.43</credit></user>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);

foreach ($xpath->evaluate('//*[count(*) = 0]') as $node) {
  var_dump($node->nodeName);
}

*匹配元素节点,//*表示文档中的任何元素节点[count(*) = 0]将其限制为没有子元素节点的节点。

输出:

string(4) "name"
string(6) "offers"
string(6) "street"
string(3) "zip"
string(4) "city"
string(6) "credit"