我想使用XMLDOM在xml文件中保存下面的数组(“name:$ array”)。我只尝试了一个城市,效果很好。但是在将代码集成到多个阵列时。它失败。
阵 ( [0] =>排列 ( [city] =>排列 ( [0] =>瑞德特 [1] =>居尔皮普 )
[distance] =>40
)
[1] => Array
(
[city] => Array
(
[0] => Array
(
[0] => Reduit
[1] => Ebe
)
[1] => Bees Village
[2] => Phoen Trunk Rd
[3] => Riv,Phoenix
[4] => St l Rd
[5] => Geoes Guibert St
[6] => Curepipe
)
[distance] => 20 )
[2] => Array
(
[city] => Array
(
[0] => Array
(
[0] => Reduit
[1] => Riv,Phoenix
)
[1] => St l Rd
[2] => Geoes Guibert St
[3] => Curepipe
)
[distance] =>155
)
[3] => Array
(
[city] => Array
(
[0] => Array
(
[0] => Reduit
[1] => Ebene
)
[1] => Belles Village
[2] => Phoenix Trunk Rd
[3] => Riverside,Phoenix
[4] => St Paul Rd
[5] => Georges Guibert St
[6] => Curepipe
)
[distance] => 79
)
)
我的工作
function saveToXml($flatArray,$flat){
#create a domdocument
$domDocument = new DOMDocument('1.0','utf-8');
$domDocument->formatOutput = true;
$domDocument->load('result.xml');
$xpath = new DOMXPath($domDocument);
$results = $xpath->query('/mauritius/pair');
$newItem = $results->item(0);
#get length of city in file
$lengthCity = $domDocument->getElementsByTagName('city')->length;
for($i=0;$i<$lengthCity;$i++){
#check if city exist
if ($lengthCity >0 ){
#delete all city
echo $lengthCity;
foreach ($results as $result){
$city=$result->getElementsByTagName('city')->item(0);
$result->removeChild($city);
}
}
}
#loop through all values
for ($row=0; $row<$flatArray;$row++){
#addElement
$new_node = $domDocument->createElement('city');
$text_node = $domDocument->createTextNode($flat[$row]);
$new_node->appendChild($text_node);
$newItem->appendChild($new_node);
}
echo $domDocument->save('result.xml');
}
是否可以将数组转换为xml?