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, 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.
PHP json_decode() and json_encode(): Summary JSON can be handled by using inbuilt PHP functions. For example, a PHP object might be turned into JSON format file using PHP json_encode() function. For the opposite transformation, use PHP json_decode() . PHP arrays are not supported by XML but can be converted into JSON.
Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Syntax : string json_encode( $value, $option, $depth ) Parameters: $value: It is a mandatory parameter which defines the value to be encoded.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With