首页  >  文章  >  后端开发  >  PHP如何将JSON转换为XML?

PHP如何将JSON转换为XML?

Guanhui
Guanhui原创
2020-07-23 10:54:322683浏览

PHP如何将JSON转换为XML?

PHP如何将JSON转换为XML?

首先使用“file_get_content()”函数将JSON数据读取出来;

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

然后使用函数“json_decode()”将数据进行解码;

$data = json_decode($json, true);

接着循环数据拼接成XML字符串;最后写入文件中即可。

$string=""; 
foreach($data as $k=>$v){ 
    $string .="<".$k.">"; 
    //取得标签数据 
        $string .=$v; 
    $string .="</".$k.">";  
}

封装示例

<?php
$json = stream_get_contents(STDIN);
$data = @json_decode($json, false);
if (!is_array($data) && !is_object($data)) {
    echo &#39;ERROR: Invalid JSON given&#39; . PHP_EOL;
    exit(1);
}
class Exporter
{
    private $root = &#39;document&#39;;
    private $indentation = &#39;    &#39;;
    // TODO: private $this->addtypes = false; // type="string|int|float|array|null|bool"
    public function export($data)
    {
        $data = array($this->root => $data);
        echo &#39;<?xml version="1.0" encoding="UTF-8">&#39;;
        $this->recurse($data, 0);
        echo PHP_EOL;
    }
    private function recurse($data, $level)
    {
        $indent = str_repeat($this->indentation, $level);
        foreach ($data as $key => $value) {
            echo PHP_EOL . $indent . &#39;<&#39; . $key;
            if ($value === null) {
                echo &#39; />&#39;;
            } else {
                echo &#39;>&#39;;
                if (is_array($value)) {
                    if ($value) {
                        $temporary = $this->getArrayName($key);
                        foreach ($value as $entry) {
                            $this->recurse(array($temporary => $entry), $level + 1);
                        }
                        echo PHP_EOL . $indent;
                    }
                } else if (is_object($value)) {
                    if ($value) {
                        $this->recurse($value, $level + 1);
                        echo PHP_EOL . $indent;
                    }
                } else {
                    if (is_bool($value)) {
                        $value = $value ? &#39;true&#39; : &#39;false&#39;;
                    }
                    echo $this->escape($value);
                }
                echo &#39;</&#39; . $key . &#39;>&#39;;
            }
        }
    }
    private function escape($value)
    {
        // TODO:
        return $value;
    }
    private function getArrayName($parentName)
    {
        // TODO: special namding for tag names within arrays
        return $parentName;
    }}$exporter = new Exporter();$exporter->export($data);

推荐教程:《PHP

以上是PHP如何将JSON转换为XML?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn