Your json can return NULL for several reasons:
I'll list them below:
JSON_ERROR_DEPTH // A profundidade máxima da pilha foi excedida
JSON_ERROR_STATE_MISMATCH // JSON inválido ou mal formado
JSON_ERROR_CTRL_CHAR // Erro de caractere de controle, possivelmente codificado incorretamente
JSON_ERROR_SYNTAX // Erro de sintaxe
JSON_ERROR_UTF8 // caracteres UTF-8 malformado , possivelmente codificado incorretamente
See more in the manual.
To find out what problem you can do as follows:
$data = curl_exec($ch);
$data = json_decode($data, true);
curl_close($ch);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
Most of the time the problem is related to JSON_ERROR_UTF8
. And if it is, there are a few ways to try to solve it. How:
$data = curl_exec($ch);
$data = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($data));
$data = json_decode($data, true);
curl_close($ch);
There is also this script:
function safe_json_encode($value, $options = 0, $depth = 512){
$encoded = json_encode($value, $options, $depth);
switch (json_last_error()) {
case JSON_ERROR_NONE: return $encoded;
case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded';
case JSON_ERROR_STATE_MISMATCH: return 'Underflow or the modes mismatch';
case JSON_ERROR_CTRL_CHAR: return 'Unexpected control character found';
case JSON_ERROR_SYNTAX: return 'Syntax error, malformed JSON';
case JSON_ERROR_UTF8:
$clean = utf8ize($value);
return safe_json_encode($clean, $options, $depth);
default: return 'Unknown error';
}
}
function utf8ize($mixed) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} else if (is_string ($mixed)) {
return utf8_encode($mixed);
}
return $mixed;
}
What would you use like this:
$data = curl_exec($ch);
$data = isafe_json_encode($data);
$data = json_decode($data, true);
curl_close($ch);
Useful links:
p>
link