我在将XML转换为数组时遇到问题

时间:2013-04-09 19:16:51

标签: php xml

我是PHP的新手,所以对我很轻松;)

基本上我有一个XML文件,我试图使用PHP将其转换为数组。我的XML文件 supplies.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 数组。

我花了将近一个小时试图让它上班,但我放弃了,希望得到一些帮助。感谢。

2 个答案:

答案 0 :(得分:1)

简单的三线解决方案:

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

但是,如果不是绝对必要的转换到数组,我宁愿将数据保存在SimpleXMLElement对象中。

答案 1 :(得分: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
                )
            ...

因此您无需在查询前添加根节点Supplies