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.