How to convert ordinary data into json data in php

PHP API interface necessary to output json format data

In daily development work, it is inevitable to write interfaces. The output of json format text is something that must be mastered when making interfaces. The current popular interfaces basically use json format data, simple php json file output

How to generate json interface? Or how to convert ordinary data into json data?

Note: If you directly output the value of json_encode without adding a header, the returned string is not an object. The js side needs to convert eval(‘(‘ + data + ‘)’) into an object first, and then get the value.

<?php
header('content-type:application/json;charset=utf8');

$arr=array(
array(

'name'=>'zhangsan',
'sex' =>'man',
'age' =>18,
),

array(
'name'=>'lisi',
'sex' =>'women',
'age' =>20,
),

array(
'name'=>'wangwu',
'sex' =>'man',
'age' =>19,
),

);

$json=json_encode($arr);
echo $json;

?>

In this way, we can get a page whose output is in json format

How to call json data in php, creation and calling of json data interface in php_is Xiaogu’s blog-CSDN blog

Use php to make a simple interface, the client passes in data, and the interface returns JSON format data

Use php to create json data interface

<?php

/*
* (PHP simply encapsulates JSON data interface)
* @param integer $code status code
* @param string $message prompt message
* @param array $data data
* return json(string)
*/

header('content-type:application/json;charset=utf8');

class Response {
    public static function json($code, $message = '', $data = []){

        # Determine parameter validity and error handling
            // code...
        
        # Result (final array)
        $result = [
            "code" => $code,
            "message" => $message,
            "data" => $data
        ];

        # Convert to json and print test
        echo json_encode($result);
        exit;
    }
}

#Create array
$arr = [
    "id" => "1",
    "name" => "wang"
];

# Call the json interface (assuming status code 200 represents success)
Response::json(200, "Data returned successfully", $arr);

?>

In this way, we can get a page whose output is in json format

<?php
    header('Content-Type:application/json;charset=utf8');
    $arr = [
        "download_url" => "http://xxx.xxx.xxx.xxx/update/EasyClick/release.iec",
        "version" => "1.1.0",
        "dialog" => true,
        "msg" => "Update announcement",
        "force" => false
    ];
    echo json_encode($arr);
?>

PHP json_encode() is used to JSON encode variables. If the function is executed successfully, it returns JSON data, otherwise it returns FALSE.

The PHP json_decode() function is used to decode a string in JSON format and convert it to a PHP variable.

<?php

header('content-type:application/json;charset=utf8');

   $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   $en_ret = json_encode($arr);
   echo $en_ret;

   echo "<br>";
   $de_ret = json_decode($en_ret);
   echo $de_ret->e;
   echo "<br>";

  
?>

JSON values can be:

  1. Number (integer or float)
  2. String (in double quotes)
  3. logical value (true or false)
  4. Array (in square brackets)
  5. object (in curly braces)
  6. null.

The front end generally chooses JSON to transfer data to the back end because

(1) JSON is a plain text format that is independent of language and platform.

(2) Generation and parsing are simpler than XML.

(3) Reading and writing are faster.

If the json_encode encoding in php is successful, it will return a string in JSON format. If it fails, it will return false (var_dump to see if it is a string type)
The backend returns the json data (string) to the front end, and the front end then performs the next step on the json data, which is the string.

And json_decode($jsondata,bool) generally decodes the json data (string) transmitted from the front desk into an object type (when bool is false, the default is false). When bool is true, json(string) Convert to array type before proceeding to the next step.

The operations on object types are different from those on array types

<?php

        header('content-type:application/json;charset=utf8');
        $data = array('a'=>'good','b'=>'hi','c'=>'good','d'=>'nice');
        $jsondata = json_encode($data,JSON_UNESCAPED_UNICODE);//Adding JSON_UNESCAPED_UNICODE will not automatically encode Chinese
        echo $jsondata;
        //Result {"a":"good","b":"hi","c":"good","d":"nice"}, a string in JSON format
        
        $array = json_decode($jsondata,TRUE);
        var_dump($array['b']);//Call array elements
        
        $obj = json_decode($jsondata);
        var_dump($obj->c);//Call object element


  
?>

Note: json_encode and json_decode only support utf-8 encoded Chinese characters. GBK Chinese characters must be converted if you want to use json.
PHP5.4 version has added a new option to Json: JSON_UNESCAPED_UNICODE. After adding this option, Chinese will not be automatically encoded.

Convert PHP arrays to JSON

Convert PHP arrays and JSON to each other, array to json: json_encode(); json to array: json_decode();

When using json_encode to convert json, you will find that Chinese characters will be garbled.

Just add JSON_UNESCAPED_UNICODE to the json_encode(); function.

1. Convert PHP array to JSON

<?php

//header('content-type:application/json;charset=utf8');

$array = Array('title' => 'title', 'url' => 'meitu.jpg');
$json = json_encode($array);
echo $json;
//Output results: {"title":"\标\题","url":"meitu.jpg"}


  
?>

2. Convert PHP array to JSON Chinese characters without garbled characters

<?php

//header('content-type:application/json;charset=utf8');

$array = Array('title' => 'title', 'url' => 'meitu.jpg');
$json = json_encode($array, JSON_UNESCAPED_UNICODE);
echo $json;
//Output result: {"title":"title","url":"meitu.jpg"}


  
?>

3. PHP JSON to array

<?php


$json = '{"title":"title","url":"meitu.jpg"}';
$array_json=json_decode($json,true);
print_r($array_json);



  
?>

4. PHP JSON to object

<?php


$json = '{"title":"title","url":"meitu.jpg"}';
$Object_json=json_decode($json,false);
print_r($Object_json);




  
?>