18

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?

chris
  • 34,442
  • 50
  • 136
  • 244

3 Answers3

13

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);
        }
    }
}
Bill
  • 4,133
  • 8
  • 27
  • 31
Michael Yurin
  • 911
  • 12
  • 17
12

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!

Community
  • 1
  • 1
linuxeasy
  • 5,771
  • 6
  • 31
  • 39
4

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.

Community
  • 1
  • 1
Pankucins
  • 1,670
  • 1
  • 16
  • 25