Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON output accents issue

I've been searching around for like 3 hours and I know there are a lot of questions like this one that have already been asked, but I haven't found any solution that works for me with my problem when trying to output accented characters of the result by a SELECT query on my database.

 $itemsList = array();
 while($row = mysql_fetch_assoc($res)){
    $itemsList[Items][] = ($row);
 }
 echo json_encode($itemsList);

This will output :

{"Items":  [

{"user_name":"misterP", 

"comment":"\u00c3\u00a9t\u00c3\u00a9",

"image_name":"403885300736874.jpg"}]}

But I need to output the accents, like this :

{"Items":  [

{"user_name":"misterP", 

"comment":"été",

"image_name":"403885300736874.jpg"}]}
  • My database and tables have interclassement utf8_general_ci
  • The datas inserted in my database are utf8_encoded
  • my php script is in Unicode (UTF-8)
  • I did " mysql_set_charset( 'utf8' ); " before the SELECT on my database
  • If this can help someone : in y database, the word "été" is : "été"

So I really don't know what to do now, I am really stuck with the accents and i can't get it work. Thanks in advance !

like image 664
Seb83 Avatar asked Dec 11 '12 18:12

Seb83


1 Answers

That doesn't really matter. When the json is decoded, they become characters again.

If you use php 5.4 >=, you can pass JSON_UNESCAPED_UNICODE to json_encode:

json_encode( $data, JSON_UNESCAPED_UNICODE )

But again, the unicode escapes work just as well and make the data ascii safe.

Edit:

It looks like your data was already screwed, even before json_encode. You have "double encoded" it as utf-8 it seems.

The datas inserted in my database are utf8_encoded

Are you using something like utf8_encode? You do not need to do anything in your code when you insert into your database. If you inserted the data in the database using utf8_encode, then that explains the double encoding. All you need is for the data to be utf-8 and have mysql_set_charset( 'utf8' ) before inserting.


It is interesting to know that if your json has unescaped unicode, the json cannot be executed as javascript even if you add parentheses if the json contains U+2028 or U+2029.

like image 124
Esailija Avatar answered Sep 18 '22 21:09

Esailija