且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 XML 转换为 PHP 多维数组

更新时间:2023-02-14 12:55:57

为什么不用 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>