gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:37:28 26 4
gpt4 key购买 nike

我有一个 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 呼应元素名称和值。请注意,元素之间的空格很重要,因此为了演示的目的,XML 被压缩了。您可能会发现从文件加载时出现类似的问题,因此如果您没有获得预期的输出,您可能需要去除空白节点。

您可以替换 //root/*用不同的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
}
}
}
?>

关于php simple xml 如何读取具有不同子节点级别的多个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6611702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com