Home >Backend Development >PHP Tutorial >Why is my JSON Decode Returning NULL Despite a Seemingly Valid JSON Response from my Web Service?
JSON Decoding Fails with Null Response from Webservice
A peculiar issue occurs when using json_encode and json_decode to handle JSON data in a web service application. The web service returns JSON in the following format:
var_dump($foo): string(62) "{"action":"set","user":"123123123123","status":"OK"}"
Upon attempting to decode the JSON in the client application using the following code:
$data = json_decode($foo, true)
the result is surprisingly null:
var_dump($data): NULL
One potential cause behind this issue lies in the PHP magic quotes configuration on the server. In PHP versions prior to 5.4, magic quotes automatically escaped certain characters in form submissions, including JSON input. To resolve this issue, disable magic quotes using the following code:
if(get_magic_quotes_gpc()){ $param = stripslashes($_POST['param']); }else{ $param = $_POST['param']; } $param = json_decode($param,true);
This should resolve the issue and allow json_decode to return the expected JSON object as expected.
The above is the detailed content of Why is my JSON Decode Returning NULL Despite a Seemingly Valid JSON Response from my Web Service?. For more information, please follow other related articles on the PHP Chinese website!