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 😮
Glad to help!
Thanks, worked like a charm
WARNING utf8_encode take latin-1 as an input, if your input come from a source that provide something else than latin-1, you should use iconv.
Thank you johnro. This is what i’m looking for