2015-05-15 38 views
1

我有一個內部包含一些SimpleXMLElement對象的數組,現在我需要爲Ajax交互獲取格式良好的XML,我該怎麼辦?PHP使用SimpleXMLElement對象將數組轉換爲XML

這是數組:

Array ( 
    [0] => SimpleXMLElement Object (
      [count] => 2 
      [id] => 20 
      [user_id] => 2 
      [title] => Polo RL) 
    [1] => SimpleXMLElement Object ( 
      [count] => 3 
      [id] => 19 
      [user_id] => 4 
      [title] => tshirt fitch) 
    [2] => SimpleXMLElement Object ( 
      [count] => 2 
      [id] => 18 
      [user_id] => 2 
      [title] => Polo La Martina) 
) 

我會得到這個XML結果:

<root> 
    <record> 
     <count>2</count> 
     <id>20</id> 
     <user_id>2</user_id> 
     <title>Polo RL</title> 
    </record> 
    <record> 
     <count>3</count> 
     <id>19</id> 
     <user_id>4</user_id> 
     <title>tshirt fitch</title> 
    </record> 
    <record> 
     <count>2</count> 
     <id>18</id> 
     <user_id>2</user_id> 
     <title>Polo La Martina</title> 
    </record> 
</root> 
+0

而且你已經嘗試 –

+0

在哪裏創建數組你的代碼? – Ghost

+0

在這裏發現了很多「從數組轉換爲xml」的方法,但沒有人在數組中有一個SimpleXMLElement對象,對於我的簡短回答抱歉,但我沒有那麼多時間! – MattC

回答

2

我會用的SimpleXMLElement的asXML方法輸出每個object.So本的XML:

$xml = <<<XML 
<record> 
    <count>2</count> 
    <id>20</id> 
    <user_id>2</user_id> 
    <title>Polo RL</title> 
<record>  
XML; 

$xml = new SimpleXMLElement($xml); 

echo $xml->asXML(); 

輸出結果如下:

<record> 
    <count>2</count> 
    <id>20</id> 
    <user_id>2</user_id> 
    <title>Polo RL</title> 
<record> 

所以,你可以簡單地通過您的陣列outputing每個XML元素的變量,像這樣的循環:

$fullXml = '<root>'; 
foreach($arrXml as $xmlElement){ 
    $fullXml .= str_replace('<?xml version="1.0"?>', '',$xmlElement->asXML()); 
} 
$fullXml .= '</root>'; 
echo $fullXml ; 
+0

謝謝!這正是我需要的! – MattC