PHP Programming

PHP Warning: json_encode() [function.json-encode]: Invalid UTF-8 sequence in argument in god_i_hate_this.php

Ever get the following error?

  • PHP Warning: json_encode() [function.json-encode]: Invalid UTF-8 sequence in argument in…

Then you are in the same boat I was in, and unfortunately for me, the solution wasn’t as straightforward as I thought it was. The problem we are seeing is that the value being encoded to json is not UTF-8 encoded data. PHP function json_encode, unfortunately, will only accept UTF-8 as its parameter.
If you search online, you will find that most people solve this problem by using the PHP function utf8_encode. This is fine and dandy if the data you deal with only contains regular alphanumerical characters (letters and numbers), but what if it contains characters from foreign languages? utf8_encode will most certainly return unwanted values, and this is not what you want.

Using utf8_encode is the right idea, but you don’t want to call the function on all your values, just the ones that require it.

$value = mb_check_encoding($value, 'UTF-8') ? $value : utf8_encode($value);

For my solution, we use mb_check_encoding to check the value to see if it’s of UTF-8 encoding, and if it’s not, then use utf8_encode. By using this, you are limiting the use of utf8_encode on only the values that require the encode, thus lifting the PHP warnings when using json_encode.


5 replies on “PHP Warning: json_encode() [function.json-encode]: Invalid UTF-8 sequence in argument in god_i_hate_this.php”

Hey John Ro … your catch really helped me.. thanx mate…. Jst the thing that i had to deal with an array, and md_check_encoding function don’t accept array as parameter…

Anyways keep posting such gr8 things.. thanx 😮


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s