Cyrillic in json_encode

The json_encodefunction encodes Cyrillic utf-8 as \u..... How to make it encode characters “as is”?

Note: not using the second parameter json_encodeand mb-functions.

Answer 1, authority 100%

From version 5.4.0 PHP introduced the JSON_UNESCAPED_UNICODEflag and everything became much simpler:

json_encode($array, JSON_UNESCAPED_UNICODE);

Answer 2, authority 25%

I had to write my own function. I hope I didn’t mess 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');

Indicate Content-Typeyour own, according to the situation

Answer 4, authority 5%

I will assume that the data comes from a database. In this case, when connecting to the database, you must specify the connection encoding – UTF-8.


Answer 5, authority 5%

I was looking for how to solve the problem, in the end it worked when I added the flag – JSON_UNESCAPED_UNICODE to json_encode
and changed the encoding when outputting

header('Content-Type: application/json; charset=utf-8');

Answer 6, authority 2%

No way.

  • Improved JSON extension: . Added new json_encode() option
    (Alexander, Gwynne)

Answer 7

Here is a recursive function that can convert all strings in array and object to UTF-8:

public function utf8ize($data) {
    if (is_array($data))
        foreach ($data as $key => $value)
            $data[$key] = $this->utf8ize($value);
    else if(is_object($data))
        foreach ($data as $key => $value)
            $data->$key = $this->utf8ize($value);
        return utf8_encode($data);
    return $data;

Also json_last_error() can be helpful in debugging json_encode()/json_encode() functions.