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?

2
  • stackoverflow.com/questions/1397036/… Commented Mar 3, 2012 at 9:09
  • How would you want to convert a JSON/array into a XML? Can you give an example? Commented Mar 3, 2012 at 9:17

3 Answers 3

14

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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!

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.