在我开始之前,我知道有很多类似的问题,但请相信我,我阅读了所有问题,如果不是大部分的话。我尝试了很多解决方案,但似乎都不起作用。我的结果是一棵空白的“树”。这是我正在使用的代码。
$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 数组。
我不确定为什么它不起作用。这是我使用该函数时的结果。
<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);
关于php - 如何将 jSON 转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964136/