What is the purpose of using json_decode in PHP and what are the potential pitfalls associated with it?
The purpose of using json_decode in PHP is to decode a JSON string and convert it into a PHP variable or object. Potential pitfalls associated with json_decode include malformed JSON strings causing errors, unexpected data types being returned, and the possibility of running into memory limits when decoding large JSON strings.
$json_string = '{"key": "value"}';
$decoded_data = json_decode($json_string);
if ($decoded_data === null && json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Error decoding JSON: ' . json_last_error_msg());
}
// Now you can use $decoded_data as a PHP variable