将xml转换为数组,无法处理节点内的节点
我想将 xml 脚本转换为 PHP 中的关联数组。 XML 脚本是:
<ages>
<Peter>
<Peterchild>4</Peterchild>
<Peterchild>6</Peterchild>
</Peter>
<Quagmire>30</Quagmire>
<Joe>34</Joe>
</ages>
我编写的用于将其转换为数组的代码是,
${$xml->getName()} = array();
foreach($xml->children() as $child){
$ages[$child->getName()] = (string)$child;
}
它给出的输出为
Array
(
[Peter] =>
[Quagmire] => 30
[Joe] => 34
)
问题是我无法找出递归遍历孩子的孩子的条件(在本例中是 Peter 的孩子) 。如何更改此代码以也考虑这些节点?
I want to convert a xml script into a associative array in PHP. The XML script is :
<ages>
<Peter>
<Peterchild>4</Peterchild>
<Peterchild>6</Peterchild>
</Peter>
<Quagmire>30</Quagmire>
<Joe>34</Joe>
</ages>
and the code i wrote for converting it to an array is
${$xml->getName()} = array();
foreach($xml->children() as $child){
$ages[$child->getName()] = (string)$child;
}
which gives the output as
Array
(
[Peter] =>
[Quagmire] => 30
[Joe] => 34
)
The problem is that I am unable to figure out a condition to recursively traverse through the children of children (children of Peter in this example). How to I change this code to consider those nodes as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要创建一个解析一个级别的函数,然后让该函数在找到当前级别内的节点时调用自身。它非常复杂并且可能会变得混乱。出于好奇,当您可以使用 SimpleXML 对象以对象格式访问所需的所有信息时,为什么要这样做呢?
You'll need to create a function that parses one level, then have the function call itself when it finds a node inside the current level. It's pretty complex and can get messy. Out of curiosity, why would you do this when you can access all the information you need in object format using a SimpleXML object?
这仅在深度为 1 级时才有效,如果要达到更多级别,您应该编写一个函数,该函数将逐级循环。
This will only work if it is 1 level deep, if it is going to be more levels you should write a function, that will cycle through it level by level.