Understanding JSON Decoding Issue in Web Service Calls
In web service interactions, occasionally, the json_decode function returns NULL. A confounding issue arises when a web service provides JSON data that resembles:
var_dump($foo): string(62) "{"action":"set","user":"123123123123","status":"OK"}"
However, attempting to decode the JSON in the application returns NULL:
$data = json_decode($foo, true); var_dump($data): NULL
Resolving the Problem
One potential cause for this issue is PHP's magic quotes functionality. Magic quotes automatically escape special characters in form data, potentially interfering with JSON parsing. To resolve this:
if (get_magic_quotes_gpc()) { $param = stripslashes($_POST['param']); } else { $param = $_POST['param']; } $param = json_decode($param, true);
By disabling magic quotes or stripping slashes from the JSON data, the application can accurately decode the JSON and retrieve the desired information.
The above is the detailed content of Why Does `json_decode` Return NULL Despite Valid-Looking JSON Data?. For more information, please follow other related articles on the PHP Chinese website!