Archive for March 16th, 2010
json decode fails on non utf-8
by z3n on Mar.16, 2010, under Coding, Tips & Hints
Problem:
When sending a non utf-8 string as json, the decoding fails.
Solution:
PHP works as utf-8 as default, since i’m using strings with accents (áéíóú..) those are taken as iso-8859-1. Client-side script will not send as utf-8, not even if you force it, so the best solution is convert the json object’s encoding. You may also want to encode your string as plain chars (I use base64) to avoid issues with IE.
Code would look like this:
$json=json_decode(iconv(‘ISO-8859-1′,’UTF-8′,base64_decode($input)),true);
If you’re working with different charsets just change the iso-8859-1, remember that if you’re working with multibyte chars, such as japanese, chinese, etc, you will need to use the mb functions instead.
Sources:
Pablo Viquez (A solution pretty much like mine but for sending data instead)