2014-02-20 31 views
1

將PHP數組轉換爲XML問題。我有一個數組,當試圖將其轉換爲xml文件時,它使用「item0」「item1」計算總字段......等等。我只希望它顯示「item」「item」。下面的例子。謝謝。將PHP數組轉換爲無數字的XML

PHP代碼將數組($ store)轉換爲XML文件。

// initializing or creating array 
$student_info = array($store); 

// creating object of SimpleXMLElement 
$xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>"); 

// function call to convert array to xml 
array_to_xml($student_info,$xml_student_info); 

//saving generated xml file 
$xml_student_info->asXML('xmltest.xml'); 


// function defination to convert array to xml 
function array_to_xml($student_info, &$xml_student_info) { 
    foreach($student_info as $key => $value) { 
     if(is_array($value)) { 
      if(!is_numeric($key)){ 
       $subnode = $xml_student_info->addChild("$key"); 
       array_to_xml($value, $subnode); 
      } 
      else{ 
       $subnode = $xml_student_info->addChild("item$key"); 
       array_to_xml($value, $subnode); 
      } 
     } 
     else { 
      $xml_student_info->addChild("$key","$value"); 
     } 
    } 
} 

什麼XML文件的樣子(與項目#錯誤)

<student_info> 
<item0> 
    <item0> 
     <bus_id>2436</bus_id> 
     <user1>25</user1> 
     <status>2</status> 
    </item0> 
    <item1> 
     <bus_id>2438</bus_id> 
     <user1>1</user1> 
     <status>2</status> 
    </item1> 
    <item2> 
     <bus_id>2435</bus_id> 
     <user1>1</user1> 
     <status>2</status> 
    </item2> 
</item0> 
</student_info> 

再次,我只是想每一個「項目」,沒有號碼顯示「項」。和第一個和最後一個「item0」......我不知道那是什麼。謝謝你的幫助!

回答

3

回答質疑

替換此:

else{ 
    $subnode = $xml_student_info->addChild("item$key"); 
    array_to_xml($value, $subnode); 
} 

與此:

else{ 
    $subnode = $xml_student_info->addChild("item"); 
    array_to_xml($value, $subnode); 
} 

回答評論

我不知道你的陣列是如何構成的,但是,從輸出中,我猜想問題是在以下行:

$student_info = array($store); 

所以改成這樣:

if (!is_array($store)) { 
    $student_info = array($store); 
} else { 
    $student_info = $store; 
} 

這應該修復它

+0

非常感謝您的幫助!它效果很好! – Rmurp006