将xml转换为数组,无法处理节点内的节点

发布于 2024-11-16 13:07:59 字数 654 浏览 3 评论 0原文

我想将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑾夏年华 2024-11-23 13:07:59

您需要创建一个解析一个级别的函数,然后让该函数在找到当前级别内的节点时调用自身。它非常复杂并且可能会变得混乱。出于好奇,当您可以使用 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?

潦草背影 2024-11-23 13:07:59
${$xml->getName()} = array();
    foreach($xml->children() as $child) 
    {
      if (count($child->children() > 0) 
      {
         foreach ($child->children as $childnode)
         {
           $ages[$childnode->getName()] = (string)$childnode;
         }
      }
      else {
          $ages[$child->getName()] = (string)$child;
      }
   }

这仅在深度为 1 级时才有效,如果要达到更多级别,您应该编写一个函数,该函数将逐级循环。

${$xml->getName()} = array();
    foreach($xml->children() as $child) 
    {
      if (count($child->children() > 0) 
      {
         foreach ($child->children as $childnode)
         {
           $ages[$childnode->getName()] = (string)$childnode;
         }
      }
      else {
          $ages[$child->getName()] = (string)$child;
      }
   }

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文