Home > Article > Backend Development > How to convert JSON file to XML format in PHP
How to convert JSON file to XML format in PHP
First get the characters in the JSON file;
$content = file_get_contents('./data.json');
Then use The function "json_decode()" converts the string into an array;
$content = file_get_contents('./data.json'); $data = json_decode($content, true);
then loops the array into XML data;
$content = file_get_contents('./data.json'); $data = json_decode($content, true); function xml_encode($data) { $string=""; foreach($data as $k => $v){ $string .= "<" . $k . ">"; //判断是否是数组,或者,对像 if(is_array($v) || is_object($v)){ //是数组或者对像就的递归调用 $string .= xml_encode($v); }else{ //取得标签数据 $string .=$v; } $string .= "" . $k . ">"; } return $string; } $content = xml_encode($data);
Finally writes the XML data into the file and changes the suffix name Just "xml".
$content = file_get_contents('./data.json'); $data = json_decode($content, true); function xml_encode($data) { $string=""; foreach($data as $k => $v){ $string .= "<" . $k . ">"; //判断是否是数组,或者,对像 if(is_array($v) || is_object($v)){ //是数组或者对像就的递归调用 $string .= xml_encode($v); }else{ //取得标签数据 $string .=$v; } $string .= "" . $k . ">"; } return $string; } $content = xml_encode($data); file_put_contents('./data.xml', $content);
Recommended tutorial: "PHP Tutorial"
The above is the detailed content of How to convert JSON file to XML format in PHP. For more information, please follow other related articles on the PHP Chinese website!