PHP使用SimpleXMLElement对象将Array转换为XML

时间:2015-05-15 14:35:26

标签: php arrays xml simplexml

我有一个包含一些SimpleXMLElement对象的数组,现在我需要为Ajax交互获得格式良好的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>

1 个答案:

答案 0 :(得分:2)

我会使用SimpleXMLElement的asXML方法输出每个对象的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>

所以你可以简单地遍历你的数组,将每个元素xml输出到一个变量,如下所示:

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