3

I need to encode a result from a MySQL query to JSON format.

My database is in the encoding utf8_unicode_ci.

In particular, I have some special chars (for example, €) stored in my database which produce a null value when I apply the PHP function json_encode.

How can I fix this?

TRiG
  • 10,148
  • 7
  • 57
  • 107
Dany
  • 2,290
  • 8
  • 35
  • 56
  • Related: [How to keep json_encode() from dropping strings with invalid characters](http://stackoverflow.com/questions/4663743/how-to-keep-json-encode-from-dropping-strings-with-invalid-characters) – Pekka Apr 26 '11 at 09:06

1 Answers1

6

My blind guess is that your MySQL database connection is not set to UTF-8, which leads to ISO-8859-1 characters being returned even if the source database is UTF-8.

Those characters will break json_encode() because they are invalid in the UTF-8 character set, which json_encode() expects.

You will probably have to set your connection encoding to UTF-8. How to do that depends on the library you are using.

In the mysql_* family of functions, one way is

mysql_query("SET names utf8;");

or in MySQL > 5.0.7, the new

mysql_set_charset("utf8");
Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088