Home > Article > Backend Development > How to convert JSON string to PHP variable? (code example)
You can use the built-in function in PHP: json_decode() function to convert JSON-encoded strings into PHP variables. The following article will introduce you to the json_decode() function. I hope it will be helpful to you.
PHP json_decode() function
json_decode() function can be used to decode a JSON string; it Can accept a JSON encoded string and convert it to a PHP variable (object or array).
Basic syntax:
json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )
Parameters: json_decode() function accepts 4 parameters
● json: use Contains the JSON string that needs to be decoded. It only works with UTF-8 encoded strings.
●assoc: This is a Boolean variable and can be omitted. The default value is false, returning a value of object type; if the value is true, the returned object will be converted to an associative array type.
●depth: used to indicate the recursion depth specified by the user.
● Options: Binary mask, the bit masks that can be included are: JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING, JSON_THROW_ON_ERROR.
Return value: This function returns the encoded JSON value in the appropriate PHP type. If the json cannot be decoded or the encoded data is deeper than the recursion limit, NULL is returned.
json_decode() function usage example
The following is a code example to see how the json_decode() function converts a JSON string into PHP variable.
Example 1:
<?php // JSON编码的字符串 $json = '{"a":7, "b":5, "c":5, "d":11, "f":19}'; // 使用json_decode()函数对JSON字符串进行解码 //转换成对象类型 var_dump(json_decode($json)); //转换成数组类型 var_dump(json_decode($json, true)); ?>
Output:
Example 2:
<?php // JSON编码的字符串 $json = '{"Coding_id": 85421545}'; // 使用json_decode()函数对JSON字符串进行解码 $obj = json_decode($json); // 显示JSON对象的值 print $obj->{'Coding_id'}; ?>
Output:
85421545
Related recommendations: "PHP Tutorial"
The above is the entire content of this article, I hope it can be helpful to everyone's learning help. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to convert JSON string to PHP variable? (code example). For more information, please follow other related articles on the PHP Chinese website!