Home >Backend Development >PHP Problem >How to convert JSON file to XML format in PHP

How to convert JSON file to XML format in PHP

Guanhui
GuanhuiOriginal
2020-05-12 17:13:443408browse

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 .= "";  
    }

    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(&#39;./data.json&#39;);

$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 .= "";  
    }

    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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn