[英]PHP convert Array with SimpleXMLElement Object to XML
I have an array with some SimpleXMLElement Objects inside and now i need to get a well formed XML for Ajax interaction, how can i do? 我有一个内部带有一些SimpleXMLElement对象的数组,现在我需要获取格式良好的XML以进行Ajax交互,该怎么办?
This is the array: 这是数组:
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 )
)
I would get this XML result: 我将得到以下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>
I would use SimpleXMLElement's asXML method to output the XML of each object.So this: 我将使用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();
Will output this: 将输出以下内容:
<record>
<count>2</count>
<id>20</id>
<user_id>2</user_id>
<title>Polo RL</title>
<record>
So you can simply loop through your array outputing each elements xml to a variable like so: 因此,您可以简单地遍历数组,将每个元素xml输出到变量,如下所示:
$fullXml = '<root>';
foreach($arrXml as $xmlElement){
$fullXml .= str_replace('<?xml version="1.0"?>', '',$xmlElement->asXML());
}
$fullXml .= '</root>';
echo $fullXml ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.