php简单xml如何读取具有不同子节点级别的多个节点
我有一个 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 />";
}
I have an xml file that has different named nodes and multi level child nodes (that are different between each node.) How should I access the data? Will it require many nested for loops?
Here is a sample of the xml code:
<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>
Here is my code so far:
$xml = simplexml_load_file("file.xml");
echo $xml->getName() . "start_info";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一些示例代码,我希望它们能为您指明正确的方向。本质上,它是遍历
DOMDocument
回显元素名称和值。请注意,元素之间的空格很重要,因此为了演示的目的,XML 被压缩了。您可能会发现从文件加载类似的问题,因此如果您没有获得预期的输出,您可能需要删除空白节点。您可以将
//root/*
替换为不同的 XPath例如//people
如果您只需要
元素。Here is some example code that I hope can point you in the right direction. Essentially, it is walking the
DOMDocument
echoing the element name and values. Note that the whitespace between the elements is significant, so for the purposes of the demo, the XML is compacted. You may find a similar issue loading from a file, so if you are not getting the expected output you might need to strip whitespace nodes.You could replace the
//root/*
with a different XPath for example//people
if you only wanted the<people>
elements.检查这个
check this