What is the usage of php json_decode?

The json_decode() function in PHP is used to convert a JSON formatted string into a PHP variable. Its syntax is:

mixed json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)

Description of parameters:

  1. $json: JSON string that needs to be decoded.
  2. $assoc (optional): default is false, specifies whether to convert the returned object into an associative array. If set to true, it will return an associative array; if set to false, it will return an object.
  3. $depth (optional): Default is 512, specifies the maximum possible nesting depth during decoding process.
  4. $options (optional): Default value is 0, specify additional options for decoding.

Example usage:

$jsonString = '{"name":"John", "age":30, "city":"New York"}';
$decodedData = json_decode($jsonString);

// 访问解码后的数据
echo $decodedData->name;  // 输出:John
echo $decodedData->age;  // 输出:30
echo $decodedData->city;  // 输出:New York

// 将返回的数据转换为关联数组
$decodedDataArray = json_decode($jsonString, true);
echo $decodedDataArray['name'];  // 输出:John
echo $decodedDataArray['age'];  // 输出:30
echo $decodedDataArray['city'];  // 输出:New York

It is important to note that if a JSON string cannot be decoded, the json_decode() function will return null. You can use the json_last_error() function to get information on any errors that occurred during the decoding process.

广告
Closing in 10 seconds
bannerAds