How to json_encode array with french accents? How to json_encode array with french accents? json json

How to json_encode array with french accents?


I found this to be the easiest way to deal with it

echo json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

JSON_PRETTY_PRINT - makes is readable
JSON_UNESCAPED_UNICODE - encodes characters correctly
JSON_UNESCAPED_SLASHES - gets rid of escape slash '\'
also notice that these option are separated by a pipe '|'


json_encode only wants utf-8. Depending on your character set, you can use iconv or utf8_encode before calling json_encode on your variable. Probably with array_walk_recursive.

As requested, an unfinished way to alter an array, with the assumptions that (1) it doesn't contain objects, and (2) the array keys are in ascii / lower bounds, so can be left as is:

$current_charset = 'ISO-8859-15';//or what it is nowarray_walk_recursive($array,function(&$value) use ($current_charset){     $value = iconv('UTF-8//TRANSLIT',$current_charset,$value);});


Another solution would be to use htmlentities or utf8_encode before using json_encode to pass the encoded char

like this:

   $array = array('myvalue' => utf8_encode('ééàà'));   return json_encode($array);

Or using htmlentities :

   $array = array('myvalue' => htmlentities('ééàà'));   return json_encode($array);