Home > Article > Backend Development > Convert php variables to json format data
In the last article we introduced "Mastering arrays in PHP (with code analysis)", in this article we will introduce json
, json
It is a lightweight data exchange format that has been widely used by most languages. When exchanging data with the front end in php
, data in the json
format is used. So how to This article will take you to take a look at how to convert variables into json format in PHP. Using json in php
requires the use of two functions json_encode
and json_decode.
1.json_decode
json_decode ( string $json , bool $assoc = false , int $depth = 512 , int $options = 0 )
$json: A string in json string format to be decoded. This function can only handle UTF-8 encoded data.
assoc: When this parameter is true, array will be returned instead of object.
depth: Specify the recursion depth.
options: A mask composed of constants.
Return value: Returns the data encoded in json via the appropriate PHP type.
2.json_encode
json_encode ( mixed $value , int $options = 0 , int $depth = 512 )
value: value to be encoded, Can be any data type except resource type. The encoding of all string data must be UTF-8.
options: A binary mask consisting of the following constants
depth: Set the maximum depth. Must be greater than 0.
Return value: Returns a JSON-encoded string on success or false on failure.
Code example:
<?php $arr = array ('a'=>"sdf",'b'=>2,'c'=>"dfasd",'d'=>4,'e'=>5); echo json_encode($arr); echo "<br>"; $js=json_encode($arr); var_dump(json_decode($js)); ?>
输出: {"a":"sdf","b":2,"c":"dfasd","d":4,"e":5} object(stdClass)#1 (5) { ["a"]=> string(3) "sdf" ["b"]=> int(2) ["c"]=> string(5) "dfasd" ["d"]=> int(4) ["e"]=> int(5) }
Recommendation: 《 Summary of PHP interview questions in 2021 (Collection)》《php video tutorial》
The above is the detailed content of Convert php variables to json format data. For more information, please follow other related articles on the PHP Chinese website!