How to parse a JSON string in PHP?

In PHP, the json_decode() function can be used to parse a JSON string. This function converts a JSON string into a PHP object or array, depending on the second parameter. If the second parameter is set to true, the JSON string will be parsed into an associative array; otherwise, it will be parsed into an object.

Here is a simple example:

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

echo $data->name; // 输出:John
echo $data->age; // 输出:30
echo $data->city; // 输出:New York

It should be noted that if the JSON string is invalid, the json_decode() function will return null. You can use the json_last_error() function to retrieve information about the parsing error.

$jsonString = 'invalid json';
$data = json_decode($jsonString);

if ($data === null) {
    echo 'JSON解析失败:' . json_last_error_msg(); // 输出:JSON解析失败:Syntax error
}
bannerAds