json_last_error
(PHP 5 >= 5.3.0, PHP 7)
json_last_error — Retorna o último erro ocorrido
Descrição
int json_last_error
( void
)
Retorna o erro (se houver) ocorrido durante o último JSON encoding/decoding.
Parâmetros
Esta função não possui parâmetros.
Valor Retornado
Retorna um inteiro, o valor pode ser uma das seguintes constantes:
| Constant | Meaning | Availability |
|---|---|---|
JSON_ERROR_NONE |
Não ocorreu nenhum erro | |
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 | PHP 5.3.3 |
Exemplos
Example #1 json_last_error() exemplo
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';
// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
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;
}
echo PHP_EOL;
}
?>
O exemplo acima irá imprimir:
Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON
Example #2 json_last_error() com json_encode()
<?php
// An invalid UTF8 sequence
$text = "\xB1\x31";
$json = json_encode($text);
$error = json_last_error();
var_dump($json, $error === JSON_ERROR_UTF8);
?>
O exemplo acima irá imprimir:
string(4) "null" bool(true)
Veja Também
- json_last_error_msg() - Retorna uma string contento a mensagem de erro da ultima chamada de json_encode() ou json_decode()
- json_decode() - Decodifica uma string JSON
- json_encode() - Retorna a representação JSON de um valor