PHP JSON or Array to XML

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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) {
            $key = "e";
            $label = $xml->addChild($key);
            $this->arrayToXml($value, $label);
        else {
            $xml->addChild($key, $value);

Solution 2

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!

Solution 3

I am not sure about the easiest way. Both are relatively simple enough as I see it.

Here’s a topic covering array to xmlHow 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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply