Search code examples
phpxmljsonsimplexml

How do I Convert jSON to XML


Before I begin, I know there are a bunch of questions similar to this, but trust me, I read all, if not most of them. I tried a bunch of solutions, but none of them seem to work. I'm getting a blank "tree" as my result. Here is the code that I am using.

$jSON = json_decode('array here');

function array2xml($array, $xml = false)
{
    if($xml === false) {
        $xml = new SimpleXMLElement('<result/>');
    }

    foreach($array as $key => $value) {
        if(is_array($value)) {
            array2xml($value, $xml->addChild($key));
        } else {
            $xml->addChild($key, $value);
        }
    }

    return $xml->asXML();
}

Here is the jSON array that I'm using.

http://pastebin.com/pN3QwSHU

I'm not sure why it isn't working. Here is the result when I use that function.

<result>
<generated_in>155ms</generated_in>
</result>

Solution

  • Instead of feeding your function an object, try to feed an array instead:

    $jSON = json_decode($raw_data, true);
                                //  ^ add second parameter flag `true`
    

    Example:

    function array2xml($array, $xml = false){
    
        if($xml === false){
            $xml = new SimpleXMLElement('<result/>');
        }
    
        foreach($array as $key => $value){
            if(is_array($value)){
                array2xml($value, $xml->addChild($key));
            } else {
                $xml->addChild($key, $value);
            }
        }
    
        return $xml->asXML();
    }
    
    $raw_data = file_get_contents('http://pastebin.com/raw.php?i=pN3QwSHU');
    $jSON = json_decode($raw_data, true);
    
    $xml = array2xml($jSON, false);
    
    echo '<pre>';
    print_r($xml);
    

    Sample Output