2

我是 PHP 的新手,所以请放轻松;)

基本上我有一个 XML 文件,我正在尝试使用 PHP 将其转换为数组。我的 XML 文件supply.xml看起来有点像这样......

<Supplies>
    <supply name="Pen">
        <supplier name="Pen Island">http://domain.com/</supplier>
        <quantity>2000</quantity>
        <cost>100.00</cost>
    </supply>
    <supply name="Pencil">
        <supplier name="Stationary World">http://domain.com/</supplier>
        <quantity>5000</quantity>
        <cost>115.30</cost>
    </supply>
    <supply name="Paper">
        <supplier name="Stationary World">http://domain.com/</supplier>
        <quantity>100</quantity>
        <cost>10.50</cost>
    </supply>
</Supplies>

我希望它转换成具有这种结构的数组...

Array (
    [Pen] => Array (
        [supplier] => Pen Island
        [supplier_link] => http://domain.com/
        [quantity] => 2000
        [cost] => 100
    )
    [Pencil] => Array (
        [supplier] => Stationary World
        [supplier_link] => http://domain.com/
        [quantity] => 5000
        [cost] => 115.3
    )
    [Paper] => Array (
        [supplier] => Stationary World
        [supplier_link] => http://domain.com/
        [quantity] => 100
        [cost] => 10.5
    )
)

我试过这个,但 PHP 不喜欢它......

<?php

    $xml_supplies = simplexml_load_file("supplies.xml");
    $supplies = array();
    foreach ($xml_supplies->Supplies->supply as $supply) {
        $supplies[(string)$supply['name']] = array(
            "supplier" => (string)$supply->supplier['name'],
            "supplier_link" => (string)$supply->supplier,
            "quantity" => (int)$supply->quantity,
            "cost" => (float)$supply->cost
        )
    }

    print_r($supplies);

?>

我的理论是它会循环遍历每个供应元素并添加到$supplies数组中。

我花了将近一个小时试图让它工作,但我已经放弃了,需要一些帮助。谢谢。

4

2 回答 2

1

简单的三线解决方案:

<?php
$xml = simplexml_load_file("supplies.xml");
$json = json_encode($xml);
$array = json_decode($json,TRUE);

但是,如果不是绝对需要转换为数组,我更愿意将数据保存在 SimpleXMLElement 对象中。

于 2013-04-09T19:27:25.960 回答
0

只需将您的代码更改为:

foreach ($xml_supplies->supply as $supply) { ...

如果您打印$xml_supplies,您将看到它具有以下结构:

SimpleXMLElement Object
(
    [supply] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Pen
                        )

                    [supplier] => http://domain.com/
                    [quantity] => 2000
                    [cost] => 100.00
                )
            ...

所以你不需要在你的查询前面加上 root node Supplies

于 2013-04-09T19:21:56.297 回答