duanboshi1472 2014-02-25 01:51
浏览 61
已采纳

如何将数组转换为xml

I'm trying to get an xml file from a foreach loop from an array but im getting only 1 row in the xml file.

Is there another way to convert the array data to xml file in this format?

PHP:

$item = array();
        $item[] = array('CityId'    => $row['city_id'],
                        'StateId'   => $row['state_id'],
                        'CityName'  => $row['city_name']
                        );

        $break = "<br />";
        $quote = '"';
        $xml = "<data>"."
";
        foreach($item as $_item) {

            echo $xml .= "<city CityId=$quote" . $_item['CityId'] . "$quote StateId=$quote" . $_item['StateId'] . "$quote CityName=$quote" . $_item['CityName'] . "$quote />
";

        }
        $xml .= "</data>";
        $sxml = new SimpleXMLElement($xml);
        echo $output = $sxml->asXML("data.xml");

Output data.xml:

<data>
<city CityId="1" StateId="217" CityName="New York" />
<city CityId="2" StateId="218" CityName="New Jersey" />
</data>

Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • 普通网友 2014-02-25 02:03
    关注

    Data :

     $cities = array(
            array(
                'cityId' => 1,
                'stateId' => 217,
                'cityName' => 'New York'
            ),
            array(
                'cityId' => 2,
                'stateId' => 0,
                'cityName' => 'Paris'
            ),
        );
    

    This :

    $xml = new SimpleXMLElement('<data/>');
    foreach ($cities as $key => $city)
    {
        $xml->city[$key]['cityId'] = $city['cityId'];
        $xml->city[$key]['stateId'] = $city['stateId'];
        $xml->city[$key]['cityName'] = $city['cityName'];
    }
    

    OR (better) :

    xml = new SimpleXMLElement('<data/>');
    foreach ($cities as $cityData)
    {
        $city = $xml->addChild('city');
        $city->addAttribute('cityId', $cityData['cityId']);
        $city->addAttribute('stateId', $cityData['stateId']);
        $city->addAttribute('cityName', $cityData['cityName']);
    }
    

    Will output :

    <data>
        <city cityId="1" stateId="217" cityName="New York" />
        <city cityId="2" stateId="0" cityName="Paris" />
    </data>
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部