0

我想将下面的数组(“名称:$array”)保存在使用 XMLDOM 的 xml 文件中。我只尝试了一个城市,效果很好。但是当将代码集成到多个数组时。它失败。

数组 ( [0] => 数组 ( [city] => 数组 ( [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
    )

)

这里是我的工作

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 ?

4

1 回答 1

0

我认为,此处给出了一个类似的答案,其中包括一个将数组转换为 XML 的函数,并且可以很容易地适应你想要做的事情。

于 2012-05-27T15:39:13.560 回答