I want to save the array below ( "name: $array" ), in an xml file using XMLDOM. I tried with only one city and it works well. But when integrating the code to multiple array. it fails.
The
Array ( [0] => Array ( [city] => Array ( [0] => Reduit [1] => Curepipe )
[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
)
)
Here my working
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');
}
is it possible to convert the array into xml ?