如何将jSON转换为XML [英] How do I Convert jSON to XML

查看:768
本文介绍了如何将jSON转换为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();
}

这是我正在使用的jSON数组.

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>

推荐答案

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

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

示例输出

这篇关于如何将jSON转换为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆