如何将json响应数据转换为xml

时间:2018-05-31 08:37:26

标签: php arrays json xml

这个响应得到一个变量,如何在php脚本中的xml中转换JSON响应

{  
   "data":[  
      {  
         "id":"15",
         "color_code":"#D9DD29",
         "font_color_code":"#ed1b1b",
         "type":"Big Chunes",
         "is_fade":"1",
         "is_Active":"1",
         "delay_time":"0"
      },
      {  
         "id":"58",
         "color_code":"#19A87D",
         "font_color_code":"#ffffff",
         "type":"Demo",
         "is_fade":"1",
         "is_Active":"1",
         "delay_time":"0"
      }
  ]
}

1 个答案:

答案 0 :(得分:0)

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 = json_decode($raw_data, true);

$xml = array2xml($jSON, false);

echo '<pre>';
print_r($xml);