Recursively convert PHP Array into XML?



I am working on a RESTful API serving content in three modes viz., JSON [most of the times], HTML [when non-api calls are made] and XML [legacy support].


My controllers return PHP arrays and then in the Views, I convert them into the desired output. PHP to JSON is done via json_encode, PHP to HTML is done via message passing between Views and Template Engine. Now, I am writing a recursive function to handle multi-dimensional PHP arrays and convert them into well formatted XML.


Following is my function:



function recursive_xml($array, \SimpleXMLElement $xmlObj){
foreach($array as $key=>$value){
$xmlObj->addChild($key);
if(!is_array($value)){
$xmlObj->$key = $value;
}
else { //Value is array
recursive_xml($value, $xmlObj->$key);
}
}
header('Content-type: text/xml');
echo $xmlObj->asXML();
} //End recursive_xml


This is working almost 80% as expected, going through arrays and creating the XML output. But the funny problem is that in the second call of the recursive_xml and there after, it appends the output in the XML and ALSO before the XML decalaration. Let's take a test case:



$obj = new \SimpleXMLElement("<root />");
$array = array("a"=>"b", "c"=>"d", "e"=>array("x"=>"z", "y"=>"v"));
recursive_xml($array, $obj);


Now the output:



`<e><x>z</x><y>v</y></e><?xml version="1.0"?>
<root><a>b</a><c>d</c><e><x>z</x><y>v</y></e></root>`


The second line of the output along with the XML declaration is what I would be ideally looking for. Any help will be deeply appreciated!


No comments:

Post a Comment