Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

php

unicode

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

like image 990
Binyamin Avatar asked Jul 21 '11 06:07

Binyamin


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is Json_unescaped_unicode?

JSON_UNESCAPED_UNICODE (int) Encode multibyte Unicode characters literally (default is to escape as \uXXXX). JSON_PARTIAL_OUTPUT_ON_ERROR (int) Substitute some unencodable values instead of failing.

Which functions are used to encode and decode JSON in PHP?

Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string.

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.


1 Answers

{"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.

like image 190
phihag Avatar answered Sep 21 '22 21:09

phihag