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条回答 默认 最新

  • 普通网友 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装