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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里