Jeff
Jeff

Reputation: 245

json_encode - Invalid UTF-8 sequence in argument

I had issue with json_encode. I was getting

PHP Warning:  json_encode() [<a href='function.json-encode'>function.json-encode</a>]: Invalid UTF-8 sequence in argument in /var/www/html/web/example.php on line 500

Then I set magic_quotes_gpc = 0 in php.ini (it was 1 before) and it stopped showing the json_encode error.

Now, I started getting the same error again. magic_quotes_gpc is 0 in php.ini. I am using PHP 5.3

I found many answers which say to convert it to UTF-8. But I cannot do it because I am using json_encode in many places and changing all is not possible.

I would like to fix the root issue so that I don't need to change the json_encode code.

In MySQL, the result for

SHOW VARIABLES LIKE 'character_set%';

is

character_set_client     latin1
character_set_connection latin1
character_set_database   latin1
character_set_filesystem binary
character_set_results   
character_set_server     latin1
character_set_system     utf8
character_sets_dir       /usr/share/mysql/charsets/

What is the reason for the json_encode error?

I am using zend server and I see this json_encode error in zend server logs.

Another thing I noticed is, even if I see the error in the server logs, it is properly converting the array to json.

There is no error in converting array to json. Then Why I see the error in zend server?

Upvotes: 2

Views: 4634

Answers (2)

Peter Pan
Peter Pan

Reputation: 58

json_encode() needs valid UTF-8 data as input.

You are feeding it invalid data.

From what you describe, you probably are getting latin1 data from your database connection, which will cause json_encode() to choke.

Set the database's connection in your script to UTF-8. How to do that depends on the database library you are using.

Here is a list of ways to switch to UTF-8 in the most common libraries: UTF-8 all the way through

Upvotes: 2

Mouhamad Ounayssi
Mouhamad Ounayssi

Reputation: 361

Try to add the instruction below after the connection parameters:

mysql_set_charset('utf8');

And for the result value:

mb_convert_encoding($result,'UTF-8','UTF-8');

Upvotes: 1

Related Questions