Tags
PHP
Asked 7 years ago
8 Oct 2016
Views 2571
hanuman

hanuman posted

UTF-8 Special Chars give null value or error with json_encode function in php


$myarray= array('nome'=>'Paição','cidade'=>'São Paulo',"À","È","Æ","Ð","Ñ","Ò","Ö",
"Ú","æ","å","ç","ì","ð","ö","ù","ü","§");
json_encode($myarray);

one server give me result

{"nome":null,"cidade":null,"0":null,"1":null,"2":null,"3":null,"4":null,"5":null,"6":null,"7":null,"8":null,"9":null,"10":null,"11":null,"12":null,"13":null,"14":null,"15":null,"16":null}

and another give me blank screen it means error . not able to encode.

so might some have solution
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

1. convert array values to html entities
2. encode json
3. decode html entities


function utf8_json_encode($json_array){
 
$json_array=array_map('htmlentities',$json_array);
 
return html_entity_decode(json_encode($json_array)); 
}



$myarray= array('nome'=>'Paição','cidade'=>'São Paulo',"À","È","Æ","Ð","Ñ","Ò","Ö",
"Ú","æ","å","ç","ì","ð","ö","ù","ü","§");
echo utf8_json_encode($myarray);

Result is

{"nome":"Paição","cidade":"São Paulo","0":"À","1":"È","2":"Æ","3":"Ð","4":"Ñ","5":"Ò","6":"Ö","7":"Ú","8":"æ","9":"å","10":"ç","11":"ì","12":"ð","13":"ö","14":"ù","15":"ü","16":"§"}


i think its perfect
ravi

ravi
answered Nov 30 '-1 00:00

encode with utf8_encode to avoid null value in json_encode function
<?php
$array= array_map(utf8_encode, $myarray);
json_encode($array)
?>
Post Answer