How to json_encode array with french accents?
I have an array item with a French accent ([WIPDescription] => Recette Soupe à lOignon Sans Boeuf US). The data is being properly pulled from the database (mysql).
However, when I try to encode this as json using the php built in json_encode it produces a null json value (OS X server: php 5.3.4开发者_JAVA技巧, json 1.2.1 enabled).
In a Linux server, the description is cut off after the first accent character.
I tried all the json_encode options with no success. Any suggestions?
Thank you.
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 now
array_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);
<?
$sql=mysql_query("SELECT * FROM TABLE...");
while($row=mysql_fetch_array($sql))
{
$output[]=array_map("utf8_encode", $row);
}
print(json_encode($output));
mysql_close();
?>
If you deal with diacritics you can also add JSON_PARTIAL_OUTPUT_ON_ERROR and it will remove only the problems and leave the rest intact. I used utf_encode before I found this but it was messing up diacritics.
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
Per the PHP docs
This function only works with UTF-8 encoded data.
$json = utf8_encode($string);
$json = json_decode($json);
精彩评论