The json_encode
function encodes the Cyrillic utf-8 as \ u ....
. How to make it encode characters “as is”?
Note: without using the second parameter json_encode
and mb-function.
Answer 1, authority 100%
Since PHP 5.4.0, the JSON_UNESCAPED_UNICODE
flag has been added and everything has become much simpler:
json_encode ($ array, JSON_UNESCAPED_UNICODE);
Answer 2, authority 25%
I had to write my own function. I hope you haven’t messed up too much?
function normJsonStr ($ str) {
$ str = preg_replace_callback ('/ \\\\ u ([a-f0-9] {4}) / i', create_function ('$ m', 'return chr (hexdec ($ m [1]) - 1072+ 224); '), $ str);
return iconv ('cp1251', 'utf-8', $ str);
}
Answer 3, authority 7%
at the beginning of the file add
header ('Content-Type: application / json; charset = utf-8');
Specify Content-Type
your own, as appropriate
Answer 4, authority 5%
I will assume that the data comes from the database. In this case, when connecting to the database, you must specify the connection encoding – UTF-8.
"mysql: host = HOST; dbname = DBNAME; charset = utf8"
Answer 5, authority 5%
I was looking for how to solve the problem, in the end it worked when I added a flag to json_encode – JSON_UNESCAPED_UNICODE
and changed the encoding when outputting
header ('Content-Type: application / json; charset = utf-8');
Answer 6, authority 2%
Nothing. http://php.net/releases/NEWS_5_4_0_beta1.txt
- Improved JSON extension:. Added new json_encode () option
JSON_UNESCAPED_UNICODE. FR # 53946.
(Alexander, Gwynne)
Answer 7
Here is a recursive function that can convert all strings in an array and object to UTF-8:
public function utf8ize ($ data) { if (is_array ($ data)) foreach ($ data as $ key = & gt; $ value) $ data [$ key] = $ this- & gt; utf8ize ($ value); else if (is_object ($ data)) foreach ($ data as $ key = & gt; $ value) $ data- & gt; $ key = $ this- & gt; utf8ize ($ value); else return utf8_encode ($ data); return $ data; }
Also json_last_error () can be useful in debugging json_encode () / json_encode () functions.