PHP 7 Script to Convert JSON to XML File in Browser Full Project For Beginners

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments

 

 

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

 

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

 

 

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);

Leave a Reply