duanboshi1472
2014-02-25 09: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条回答 默认 最新

  • dsgnsdjk26586 2014-02-25 10: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>
    
    点赞 打赏 评论
  • dpii73380 2014-02-25 10:07

    have a look here. i have been using this function to convert array to xml. hope it will help you.

    http://vantulder.net/old-articles/array-to-xml

    点赞 打赏 评论

相关推荐 更多相似问题