A lot of stuff and things…

PHP json_decode Fails on UTF and Other Encodings

I was working on a project this week and found that PHP’s json_decode function does not function properly with encoded characters. I tried a number of methods such as utf8_decode and addslashes to no avail. The location which I am stripping data from has no rhyme or reason to it’s encoding so I needed something better. I’m not going to go into why as it’s pretty obvious.
This function should help you; hopefully as much as it helped me.

$array = json_decode(safeJSON_chars($iso_8859_1_data)); 
function safeJSON_chars($data) { 
    $aux = str_split($data); 
    foreach($aux as $a) { 
        $a1 = urlencode($a); 
        $aa = explode("%", $a1); 
        foreach($aa as $v) { 
            if($v!="") { 
                if(hexdec($v)>127) { 
                $data = str_replace($a,"&#".hexdec($v).";",$data); 
    return $data; 

Next Post

Previous Post

Leave a Reply

© 2021

Theme by Anders Norén