2012-05-27 79 views
0

我想使用XMLDOM將下面的數組(「name:$ array」)保存在xml文件中。我嘗試了只有一個城市,它運作良好。但是,將代碼集成到多個陣列時。它失敗。將複雜數組轉換爲XML

陣列 ( [0] =>數組 ( [城市] =>數組 ( [0] =>瑞德特 [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?

回答

0

給出了類似的答案here其中包括一個將數組轉換爲XML的函數,並且可以很容易地適應您正在嘗試執行的操作。

+0

是的,但我唯一的問題是如何保存嵌套數組而不展平結果併合並所有內容。 – user1419210

+0

猜猜我並不完全理解這個問題,我已經使用了第二個例子,並將數組的全部深度放入一個SimpleXML對象中,並將其保存到一個文件中。 – GDP

+0

它不工作,我試過。 – user1419210