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?
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:
<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>
-
And what you have triedNarendrasingh Sisodia– Narendrasingh Sisodia2015年05月15日 14:42:15 +00:00Commented May 15, 2015 at 14:42
-
where are your codes that created the array?Kevin– Kevin2015年05月15日 14:45:37 +00:00Commented May 15, 2015 at 14:45
-
a lot of methods found here as "convert from array to xml" but no one had an SimpleXMLElement object inside an array, sorry for my short answer but i've not so much time!MattC– MattC2015年05月15日 14:49:03 +00:00Commented May 15, 2015 at 14:49
-
It was originally an XML like the one I wrote, but it was not ordered for id in descending order, then i used iterator_to_array, array_multisort and usort for order it in the right way, and now i need to go back to XMLMattC– MattC2015年05月15日 14:56:19 +00:00Commented May 15, 2015 at 14:56
-
do you want to merge them in one object? Or want to get formated string?splash58– splash582015年05月15日 15:12:41 +00:00Commented May 15, 2015 at 15:12
1 Answer 1
I would use SimpleXMLElement's asXML method to output the XML of each object.So this:
$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:
$fullXml = '<root>';
foreach($arrXml as $xmlElement){
$fullXml .= str_replace('<?xml version="1.0"?>', '',$xmlElement->asXML());
}
$fullXml .= '</root>';
echo $fullXml ;
answered May 15, 2015 at 16:58
default