使用PHP遍历DOM文档 [英] Iterate through DOM document with PHP

查看:74
本文介绍了使用PHP遍历DOM文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was simply trying to get all node names of an XML file in PHP by iterating through it. This is my attempt:

$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 

什么我做错了吗?

编辑:

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

My final plan was to add the name of the children to the name of the parent nodes seperated by "_", so the final output for the example above should be:

name
offers
address_street
address_zip
address_city
credit

最简单的方法是什么?

推荐答案

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

Not only the elements are nodes. You output the name of the nodes without children. In your XML that are text nodes only.

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

You could check the node type ... or use 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] 将其限制为没有子元素节点的节点。

* matches elements nodes, //* means any element node in the document, [count(*) = 0] limits it to nodes without child element nodes.

输出:

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

这篇关于使用PHP遍历DOM文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆