I have a JSON string with many UNICODE codes in it, I am looking for a way to convert them to UTF8 using PHP. The JSON string has values like:
{
"capital":"Bras\u00edlia",
"symbol":"\u20a1"
}
and then other values like:
{
"native": "اليَمَن",
"symbol_native": "ر.ي."
}
The JSON string is contained inside a PHP variable that looks like this:
$countries ='{
"AR":{
"name":"Argentina",
"native":"Argentina",
"phone":"54",
"continent":"SA",
"capital":"Buenos Aires",
"currency":{
"symbol":"AR$",
"name":"Argentine Peso",
"symbol_native":"$",
"decimal_digits":2,
"rounding":0,
"code":"ARS",
"name_plural":"Argentine pesos",
"vat":"21",
"vat_name":"IVA"
},
"tin":"CUIT",
"languages":"es,gn",
"iso":"ARG"
}';
Already tried most solutions around the web and SO but none of them worked, tried unsuccessfully with:
utf8_encode()
mb_convert_encoding()
iconv()
header('charset=utf-8');
The only way I found to successfully transform UNICODE codes to UTF8 was using str_replace()
creating an array of the UNICODE codes and another array with their equivalent UTF8 values, but the array I have wont cover all posible combinations, so I was wondering if there is an easier way to do it.
This one works with the characters in the array:
function unicodeToutf8($str){
$repl = ['\u00e1','\u00e9','\u00ed','\u00f3','\u00fa','\u00f1','\u00c1','\u00c9','\u00cd','\u00d3','\u00da','\u00d1'];
$with = ['á','é','í','ó','ú','ñ','Á','É','Í','Ó','Ú','Ñ'];
return str_replace($repl,$with,$str);
}
Thank you!
如果您只是想在没有 unicode 转义序列的情况下重新编码 JSON,则可以这样做:
json_encode(json_decode($input), JSON_UNESCAPED_UNICODE);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.