How to solve JSON_ERROR_UTF8 error in php json_decode?

I am trying to use this code

$json = file_get_contents("http://www.google.com/alerts/preview?q=test&t=7&f=1&l=0&e"); print_r(json_decode(utf8_encode($json), true)); ////////////// // Define the errors. $constants = get_defined_constants(true); $json_errors = array(); foreach ($constants["json"] as $name => $value) { if (!strncmp($name, "JSON_ERROR_", 11)) { $json_errors[$value] = $name; } } // Show the errors for different depths. foreach (range(4, 3, -1) as $depth) { var_dump(json_decode($json, true, $depth)); echo 'Last error: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL; } 

I tried many functions, html_entities_decode, utf8_encode and decoded, decoded hex codes, but always get the error "JSON_ERROR_UTF8".

How can i solve this?

+38
json jsonp php parsing
Apr 17 2018-12-12T00:
source share
3 answers

There is a good function to sanitize your arrays.

I suggest you use the json_encode wrapper as follows:

 function safe_json_encode($value, $options = 0, $depth = 512){ $encoded = json_encode($value, $options, $depth); switch (json_last_error()) { case JSON_ERROR_NONE: return $encoded; case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception() case JSON_ERROR_STATE_MISMATCH: return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception() case JSON_ERROR_CTRL_CHAR: return 'Unexpected control character found'; case JSON_ERROR_SYNTAX: return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception() case JSON_ERROR_UTF8: $clean = utf8ize($value); return safe_json_encode($clean, $options, $depth); default: return 'Unknown error'; // or trigger_error() or throw new Exception() } } function utf8ize($mixed) { if (is_array($mixed)) { foreach ($mixed as $key => $value) { $mixed[$key] = utf8ize($value); } } else if (is_string ($mixed)) { return utf8_encode($mixed); } return $mixed; } 

In my application, utf8_encode () works better than iconv ()

+46
Nov 05 '14 at 15:32
source share

You need a simple line of code:

 $input = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($input)); $json = json_decode($input); 

Credit: Sang Le, my team gave me this code. Yes!

+44
Jun 19 '13 at 3:31 on
source share

The iconv function is pretty useless if you cannot guarantee that the input is valid. Use mb_convert_encoding instead.

 mb_convert_encoding($value, "UTF-8", "auto"); 

You can get more explicit than "auto", and even specify a list of expected input encodings, separated by commas.

Most importantly, invalid characters will be processed without causing the entire line to be discarded (unlike iconv).

+6
Jun 25 '14 at 17:22
source share



All Articles