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

时间:2011-07-07 13:52:26

标签: php xml arrays foreach nodes

我有一个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 />";
  }

2 个答案:

答案 0 :(得分:2)

以下是一些示例代码,希望能指出正确的方向。基本上,它是DOMDocument 回显元素名称和值。请注意,元素之间的空格很重要,因此为了演示的目的,XML会被压缩。您可能会发现从文件加载类似的问题,因此如果您没有获得预期的输出,则可能需要删除空白节点。

如果您只想要//root/*元素,则可以将//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 } } } ?>

{{1}}

答案 1 :(得分:0)

检查这个

$xml_file = 'file.xml';
$xmlobj = simplexml_load_file($xml_file);
echo $xmlobj->getName() . 'start_info<br />';
foreach($xmlobj->children() as $childs) {
  echo $childs->getName(). ': '. '<br />';
  if($childs->count()>1) {
    foreach($childs as $child) {
     echo $child->getName(). ': '. $child. '<br />';
    }
  }
}