Last active
July 13, 2020 05:17
-
-
Save bharathraj-e/4ae201358388a45b54f7df6d094025de to your computer and use it in GitHub Desktop.
decode json from file_get_contents(); ,with error displaying
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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