gpt4 book ai didi

php - 如何将 jSON 转换为 XML

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:56:37 25 4
gpt4 key购买 nike

在我开始之前,我知道有很多类似的问题,但请相信我,我阅读了所有问题,如果不是大部分的话。我尝试了很多解决方案,但似乎都不起作用。我的结果是一棵空白的“树”。这是我正在使用的代码。

$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 数组。

http://pastebin.com/pN3QwSHU

我不确定为什么它不起作用。这是我使用该函数时的结果。

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

最佳答案

与其为函数提供对象,不如尝试提供数组:

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

Sample Output

关于php - 如何将 jSON 转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com