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
Release: 2023-03-01 07:38:01
Original
3396 people have browsed it

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');
Copy after login

Then use The function "json_decode()" converts the string into an array;

$content = file_get_contents('./data.json');

$data = json_decode($content, true);
Copy after login

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template