Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to convert JSON string with UNICODE codes to UTF8 using PHP

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!

like image 645
Crash Override Avatar asked Apr 20 '26 10:04

Crash Override


1 Answers

If you're just trying to re-encode the JSON without the unicode escape sequences, this is how it's done:

json_encode(json_decode($input), JSON_UNESCAPED_UNICODE);
like image 133
Evert Avatar answered Apr 22 '26 06:04

Evert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!