Reputation: 36937
Whats the easiest way to take a JSON or Array object and convert it to XML. Maybe I am looking in all the wrong places but I am not finding a decent answer to get me on track with doing it. Is this something I would have to somehow build myself? Or is there something like json_encode/json_decode that will take an array or json object and ust pop it out as a xml object?
Upvotes: 18
Views: 96607
Reputation: 1060
Here is my variant of JSON to XML conversion. I get an array from JSON using json_decode() function:
$array = json_decode ($someJsonString, true);
Then I convert the array to XML with my arrayToXml() function:
$xml = new SimpleXMLElement('<root/>');
$this->arrayToXml($array, $xml);
Here is my arrayToXml() function:
/**
* Convert an array to XML
* @param array $array
* @param SimpleXMLElement $xml
*/
function arrayToXml($array, &$xml){
foreach ($array as $key => $value) {
if(is_int($key)){
$key = "e";
}
if(is_array($value)){
$label = $xml->addChild($key);
$this->arrayToXml($value, $label);
}
else {
$xml->addChild($key, $value);
}
}
}
Upvotes: 13
Reputation: 1720
I am not sure about the easiest way. Both are relatively simple enough as I see it.
Here's a topic covering array to xml
- How to convert array to SimpleXML and many pages covering json to xml
can be found on google so I assume it's pretty much a matter of taste.
Upvotes: 4
Reputation: 6499
Check it here: How to convert array to SimpleXML
and this documentation should help you too
Regarding Json to Array, you can use json_decode to do the same!
Upvotes: 12