Using Zend_JSON for parse invalid JSON format like “pain in the neck”. If you got this kind of error while parse JSON :
1 | Uncaught exception ‘Zend_Json_Exception’ with message ‘Decoding failed: Syntax error |
Or maybe :
1 | Uncaught exception ‘Zend_Json_Exception’ with message ‘Decoding failed: Unexpected control character found |
I suggest to you, move into json_decode() from native PHP. Here are snippets to handle JSON invalid format exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function json_downloader($url) { $file = file_get_contents($url, 100000); $results = json_decode($file, true); if ($file === false) { return false; } else { switch(json_last_error()) { case JSON_ERROR_DEPTH: $error = ‘ – Maximum stack depth exceeded’; break; case JSON_ERROR_CTRL_CHAR: $error = ‘ – Unexpected control character found’; break; case JSON_ERROR_SYNTAX: $error = ‘ – Syntax error, malformed JSON’; break; case JSON_ERROR_NONE: $error = null; break; } if(empty($error)) { return $results; } else { return false; } } } |
How to use?
Just insert your URL which contain JSON into this function.
1 2 | $url = ‘put your JSON url here’; print json_downloader($url); |
Problem solved! 😀