且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将jSON转换为XML

更新时间:2023-02-14 10:21:46

与其给函数提供对象,不如给它提供数组:

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

示例输出