php创建JSON数据详解:

    <?php  
    //创建一个字符数组 
    $arr=array( 
      'id'=>1, 
      'name'=>'Qicloud'
    ); 
    echo json_encode($arr);//创建JSON的关键函数 
    ?> 

输出结果:

    {"id":1,"name":"Qicloud"}

注意: json_encode($value);这个函数只能接收utf-8编码的数据。其他格式数据传给该函数返回null;

封装通信接口的数据方法实例:

demo.php

    class Response
    {
        /**
         * 按json方式输出数据    
         * @param  integer $code 状态码
         * @param  string $msg 提示信息
         * @param  array $author  作者
         * @param  array $request  接口信息
         * @param  array  $data    数据
         * @return string          
         */
        public static function json($code, $msg = '', $author = array(), $request = array(), $data = array())
        {
            if (!is_numeric($code)) { //is_numeric()判断变量是否为数字
                return '';
            }

        $result = array(
            'code' =&gt; $code,
            'msg' =&gt; $msg,
            'author' =&gt; $author,
            'request' =&gt; $request,
            'data' =&gt; $data
        );
        @header("Content-Type: application/json; charset=utf-8");
        echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);//输出中文字符串并格式化json
        exit;
    }
}</code></pre>

调用上面的类的方法,创建json 数据

    <?php 
    require('./demo.php'); //引入
    $author = array(
            'author' => '神奇的七云',
            'url' => 'https://blog.zets.cn',
            'email' => 'admin@qqiyu.cn'
        );
        $request = array(
            'request' =>  'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
            'format' => 'json',
            'api' => 'a',
            'time' => date("Y-d-m h:i:s", time())
        );
        $data = array(
            'id' => '1',
            'content' => '一句话',
            'author' => null,
            'form' => null,
            'titie' => '嘿嘿',
            'total' => '123456',
        );
        $test = new Response(); //实例化test2.php文件中Response类
        $test->json(200, 'success', $author, $request, $data);

输出结果:

    {
        "code": 200,
        "msg": "success",
        "author": {
            "author": "神奇的七云",
            "url": "https://blog.zets.cn",
            "email": "admin@qqiyu.cn"
        },
        "request": {
            "request": "http://127.0.0.2/?type=json&c=a",
            "format": "json",
            "api": "a",
            "time": "2020-12-04 07:36:43"
        },
        "data": {
            "id": "536725",
            "content": "警告: 对方正在潜入你的心防阵地 请做好投降准备",
            "author": null,
            "form": null,
            "titie": "网络采集",
            "total": "718931"
        }
    }