Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

PhpUnicodeJson

Php Problem Overview


Any way to return PHP json_encode with encode UTF-8 and not Unicode?

$arr=array('a'=>'á');
echo json_encode($arr);

mb_internal_encoding('UTF-8');and $arr=array_map('utf8_encode',$arr); does not fix it.

Result: {"a":"\u00e1"}

Expected result: {"a":"á"}

Php Solutions


Solution 1 - Php

{"a":"\u00e1"} and {"a":"á"} are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.

In php 5.4+, php's json_encode does have the JSON_UNESCAPED_UNICODE option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters, or use http://pear.php.net/package/Services_JSON/download">Pear's</a> JSON encoder and remove line 349 to 433.

Solution 2 - Php

I resolved my problem doing this:

  • The .php file is encoded to ANSI. In this file is the function to create the .json file.
  • I use json_encode($array, JSON_UNESCAPED_UNICODE) to encode the data;

The result is a .json file encoded to ANSI as UTF-8.

Solution 3 - Php

This function found here, works fine for me

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

Solution 4 - Php

Use JSON_UNESCAPED_UNICODE inside json_encode() if your php version >=5.4.

Solution 5 - Php

just use this,

utf8_encode($string);

you've to replace your $arr with $string.

I think it will work...try this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBinyaminView Question on Stackoverflow
Solution 1 - PhpphihagView Answer on Stackoverflow
Solution 2 - PhpSheyla FernandesView Answer on Stackoverflow
Solution 3 - PhpantoniomView Answer on Stackoverflow
Solution 4 - PhpLakin MohapatraView Answer on Stackoverflow
Solution 5 - PhpAshish TikaryeView Answer on Stackoverflow