我正在尝试从数组中获取来自foreach循环的xml文件,但我在xml文件中只获得了1行。
还有另一种方法可以将数组数据转换为这种格式的xml文件吗?
PHP:
$item = array();
$item[] = array('CityId' => $row['city_id'],
'StateId' => $row['state_id'],
'CityName' => $row['city_name']
);
$break = "<br />";
$quote = '"';
$xml = "<data>"."\n";
foreach($item as $_item) {
echo $xml .= "<city CityId=$quote" . $_item['CityId'] . "$quote StateId=$quote" . $_item['StateId'] . "$quote CityName=$quote" . $_item['CityName'] . "$quote />\n";
}
$xml .= "</data>";
$sxml = new SimpleXMLElement($xml);
echo $output = $sxml->asXML("data.xml");
输出data.xml:
<data>
<city CityId="1" StateId="217" CityName="New York" />
<city CityId="2" StateId="218" CityName="New Jersey" />
</data>
感谢任何帮助。
答案 0 :(得分:1)
数据:
$cities = array(
array(
'cityId' => 1,
'stateId' => 217,
'cityName' => 'New York'
),
array(
'cityId' => 2,
'stateId' => 0,
'cityName' => 'Paris'
),
);
这:
$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'];
}
或(更好):
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']);
}
将输出:
<data>
<city cityId="1" stateId="217" cityName="New York" />
<city cityId="2" stateId="0" cityName="Paris" />
</data>
答案 1 :(得分:0)
看看这里。我一直在使用此函数将数组转换为xml。希望它会对你有所帮助。