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).
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 = utf8_encode($string);
$json = json_decode($json);
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);
});
Per the PHP docs
This function only works with UTF-8 encoded data.
<?
$sql=mysql_query("SELECT * FROM TABLE...");
while($row=mysql_fetch_array($sql))
{
$output[]=array_map("utf8_encode", $row);
}
print(json_encode($output));
mysql_close();
?>
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);