将 XML 转换为 PHP 多维数组 [英] Converting an XML into a PHP multidimensional array

查看:36
本文介绍了将 XML 转换为 PHP 多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 XML 文件中设置了以下数组:

I have the following array set in an XML file:

<?xml version="1.0"?>
<hats>
    <a id="Chicago BULLS" img="bulls.jpeg" cost="$25.00" />
    <b id="Toronto RAPTORS" img="raptors.jpeg" cost="$25.00" />
    <c id="Orlando MAGIC" img="magic.jpeg" cost="$25.00" />
</hats>
<clothes>
    <a id="Chicago BULLS 23" img="bullstee.jpeg" cost="$30.00" />
    <b id="Toronto RAPTORS 23" img="torontotee.jpeg" cost="$30.00" />
    <c id="Orlando MAGIC 23" img="magictee.jpeg" cost="$30.00" />
</clothes>

我使用了一个我发现的函数将 XML 转换为多维数组,如下所示:

I have used a function I found to convert the XML into a Multidimensional Array which looks like this:

Array
(
    [hats] => Array
        (
            [a] => Array
                (
                )

            [a_attr] => Array
                (
                    [id] => Chicago BULLS
                    [img] => bulls.jpeg
                    [cost] => $25.00
                )

            [b] => Array
                (
                )

            [b_attr] => Array
                (
                    [id] => Toronto RAPTORS
                    [img] => raptors.jpeg
                    [cost] => $25.00
                )

            [c] => Array
                (
                )

            [c_attr] => Array
                (
                    [id] => Orlando MAGIC
                    [img] => magic.jpeg
                    [cost] => $25.00
                )

        )

)

正如你所看到的,它只占用了一半的 XML 文件,而且我无法使用数字,所以不得不求助于字母.

As you can see it has only taken half of the XML file, and also I am unable to use numbers so have to resort to letters.

最终我试图让它读取 XML 文件,然后只输出标签和标签中显示的内容,最终更多.

Ultimately I am trying to have it read the XML file then output only what is shown within the tags and tags and eventually more.

如何将 XML 文件干净地解析为数组,以便我可以使用 foreach 循环来显示 XML 文件的给定部分(仅限帽子或仅限衣服)中的每一行.

How can I parse the XML file cleanly into an array so I can then use a foreach loop to show each line in a given section of the XML file (hats only or clothes only).

推荐答案

为什么不用 simplexml 直接从 XML 中读取?

Why not read directly from XML with simplexml?

$xml = simplexml_load_string($x); // assume XML in $x

foreach ($xml->children() as $name => $value) {
    echo "$name: <br />"; // name of the node, e.g. '<hats>'
    foreach ($value->children() as $item) {
        echo "$item[id], $item[img], $item[cost]<br />";
    }
}

看到这个工作:http://3v4l.org/dpjsg

如果您是此 XML 的创建者,请像这样更轻松地解析:

In case you are the creator of this XML, make it easier to parse like this:

<items>
    <group name="hats">
        <item id="1" name="Chicago BULLS" img="bulls.jpeg" cost="25.00" />
    </group>
    <group name="clothes">
        ...
    </group>
</items>

这篇关于将 XML 转换为 PHP 多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆