62

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":"á"}

hakre
  • 193,403
  • 52
  • 435
  • 836
Binyamin
  • 7,493
  • 10
  • 60
  • 82

5 Answers5

99

{"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 Pear's JSON encoder and remove line 349 to 433.

phihag
  • 278,196
  • 72
  • 453
  • 469
43

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.

Baz
  • 36,440
  • 11
  • 68
  • 94
31

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));
}
antoniom
  • 3,143
  • 1
  • 37
  • 53
  • 1
    No need of it since `JSON_UNESCAPED_UNICODE`. – Binyamin Jun 03 '13 at 18:25
  • 8
    @Binyamin, yes, but not everyone runs php 5.4 – antoniom Jun 03 '13 at 21:25
  • I tried this solution and it didn't work as i needed, but found another that solved my problem at [Convert Unicode from JSON string with PHP](http://stackoverflow.com/questions/14523846/convert-unicode-from-json-string-with-php), hope it helps anyone that needs it. – CJ Mendes Jan 02 '14 at 12:15
  • Yeah, this didnt work for me either. The result was way too many backslashes, so instead of "ÖXXX" I got "\\\ÖXXX". If I removed the json_encode at the end, I got "\ÖXXX", so one backslash too many. – Ted Jan 26 '15 at 11:47
  • **This doesn't work if** the input contains a string which contains a JavaScript Unicode Escape Sequence. For example, for the input string `"\u0059"`, applying `jsonRemoveUnicodeSequences()` gives `""\Y""` (which is invalid JSON), then applying `json_decode()` gives `NULL` instead of the original string. – Pang Mar 18 '15 at 06:43
  • 2
    `/e` for `preg_replace()` is [*deprecated* in PHP 5.5.x](http://php.net/manual/en/migration55.deprecated.php). – Pang Mar 18 '15 at 06:58
11

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

Saty
  • 22,443
  • 7
  • 33
  • 51
Lakin Mohapatra
  • 1,097
  • 11
  • 22
-4

just use this,

utf8_encode($string);

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

I think it will work...try this.

BartekR
  • 3,827
  • 3
  • 24
  • 33
Ashish Tikarye
  • 850
  • 8
  • 11