Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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.

like image 918
Natkeeran Avatar asked Aug 03 '11 15:08

Natkeeran


People also ask

What is the difference between json_encode and Json_decode?

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.

What does json_encode return?

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.

What is json_encode function?

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.


2 Answers

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 '|'

like image 153
Pete Avatar answered Sep 22 '22 01:09

Pete


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);  }); 
like image 20
Wrikken Avatar answered Sep 23 '22 01:09

Wrikken