- json_last_error_msg: documentation ( source)
- json_decode: documentation ( source)
- json_last_error: documentation ( source)
- function_exists: documentation ( source)
- ini_set: documentation ( source)
- error_reporting: documentation ( source)
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
try {
echo 'JSON decode of null: ' . json_decode(null) . PHP_EOL;
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'Last JSON error: ' . safe_json_last_error_msg() . PHP_EOL;
}
} catch (Throwable $t) {
echo 'Error from JSON decode of null: ' . $t->getMessage() . PHP_EOL;
}
try {
echo 'JSON decode of empty string: ' . json_decode('') . PHP_EOL;
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'Last JSON error: ' . safe_json_last_error_msg() . PHP_EOL;
}
} catch (Throwable $t) {
echo 'Error from JSON decode of empty string: ' . $t->getMessage() . PHP_EOL;
}
function safe_json_last_error_msg()
{
if (function_exists('json_last_error_msg')) {
return json_last_error_msg();
}
switch (json_last_error()) {
case JSON_ERROR_NONE: return 'No error';
case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded';
case JSON_ERROR_STATE_MISMATCH: return 'State mismatch (invalid or malformed JSON)';
case JSON_ERROR_CTRL_CHAR: return 'Control character error, possibly incorrectly encoded';
case JSON_ERROR_SYNTAX: return 'Syntax error';
case JSON_ERROR_UTF8: return 'Malformed UTF-8 characters, possibly incorrectly encoded';
default: return 'Unknown error';
}
}