php简单xml如何读取具有不同子节点级别的多个节点

2024-05-09

我有一个 xml 文件,其中包含不同的命名节点和多级子节点(每个节点之间都不同)。我应该如何访问数据?需要很多嵌套的for循环吗?

以下是 xml 代码示例:

       <start_info>
          <info tabindex="1">
                  <infonumber>1</infonumber>
                  <trees>green</trees>
           </info>
       </start_info>

          <people>
                <pe>
                    <people_ages>
                       <range number="1">
                          <age value="1">1</age>
                          <age value="2">2</age>
                        </range>
                    </people_ages>
                </pe>
          </people>

到目前为止,这是我的代码:

$xml = simplexml_load_file("file.xml");

echo $xml->getName() . "start_info";

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  }

这是一些示例代码,我希望它们能为您指明正确的方向。本质上,它是行走在DOMDocument http://php.net/manual/en/class.domdocument.php回显元素名称和值。请注意,元素之间的空格很重要,因此为了演示的目的,XML 被压缩了。您可能会发现从文件加载类似的问题,因此如果您没有获得预期的输出,您可能需要删除空白节点。

你可以更换//root/*与不同的XPath http://www.w3.org/TR/xpath/例如//people如果你只想<people>元素。

<?php
    $xml = <<<XML
    <root><start_info><info tabindex="1"><infonumber>1</infonumber><trees>green</trees></info></start_info>
    <people><pe><people_ages><range number="1"><age value="1">1</age><age value="2">2</age></range></people_ages></pe></people>
    </root>
    XML;

    $dom = new DOMDocument();
    $dom->recover = true;
    $dom->loadXML($xml);
    $xpath = new DOMXPath($dom);
    $nodelist = $xpath->query('//root/*');
    foreach ($nodelist as $node) {
        echo "\n$node->tagName";
        getData($node);
    }

    function getData($node) {
        foreach ($node->childNodes as $child) {

            if ($child->nodeType == XML_ELEMENT_NODE) {
                echo ($child->tagName === '' ? '' : "\n").$child->tagName;
            }

            if ($child->nodeType == XML_TEXT_NODE) {
                echo '->'.$child->nodeValue;
            }

            if ($child->hasChildNodes()) {
                getData($child); // recursive call
            }
        }
    }
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

php简单xml如何读取具有不同子节点级别的多个节点 的相关文章

随机推荐