Skip to content

Instantly share code, notes, and snippets.

@bharathraj-e
Last active July 13, 2020 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bharathraj-e/4ae201358388a45b54f7df6d094025de to your computer and use it in GitHub Desktop.
Save bharathraj-e/4ae201358388a45b54f7df6d094025de to your computer and use it in GitHub Desktop.
decode json from file_get_contents(); ,with error displaying
function decodeJson($json, $assoc = false)
{
$json = preg_replace('/[\x00-\x1F\x7F]/u', '', $json);
$ret = json_decode($json, $assoc);
if ($error = json_last_error()) {
$errorReference = [
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
JSON_ERROR_SYNTAX => 'Syntax error.',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
];
$errStr = isset($errorReference[$error]) ? $errorReference[$error] : "Unknown error ($error)";
throw new \Exception("JSON decode error ($error): $errStr");
}
return $ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment