Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use cyrillic symbols in Lumen(by Laravel)?

The issue is I can't use any russian symbols in the response()->json() method. I've already tried the following code:

return response()->json(['users' => 'тест']);

and

return response()->json(['users' => mb_convert_encoding('тест', 'UTF-8')]);

and

return response()->json(
       ['users' => mb_convert_encoding('тест', 'UTF-8')])
       ->header('Content-Type', 'application/json; charset=utf-8');

I've checked the default encoding:

mb_detect_encoding('тест'); // returns 'UTF-8'

Also, all my files have been converter to UTF-8 without BOM. I've added the default character set to the .htaccess file(AddDefaultCharset utf-8) as well.

But, I still get the wrong response like here:

{"users":"\u0442\u0435\u0441\u0442"}
like image 279
Sergey Avatar asked Dec 01 '15 20:12

Sergey


People also ask

Does UTF-8 contain Cyrillic?

UTF-8. 128 characters are encoded using 1 byte (the ASCII characters). 1920 characters are encoded using 2 bytes (Roman, Greek, Cyrillic, Coptic, Armenian, Hebrew, Arabic characters).

What is Russian encoding?

KOI8-R (RFC 1489) is an 8-bit character encoding, derived from the KOI-8 encoding by the programmer Andrei Chernov in 1993 and designed to cover Russian, which uses a Cyrillic alphabet. KOI8-R was based on Russian Morse code, which was created from a phonetic version of Latin Morse code.


1 Answers

The response that you are getting:

 {"users":"\u0442\u0435\u0441\u0442"}

is valid JSON!

That being said, if you don't want to encode the UTF-8 characters, you can simply just do this:

 $data = [ 'users' => 'тест' ];
 $headers = [ 'Content-Type' => 'application/json; charset=utf-8' ];

 return response()->json($data, 200, $headers, JSON_UNESCAPED_UNICODE);

The output would then be

 {"users":"тест"}

Why does this work?

Calling the response() helper will create an instance of Illuminate\Routing\ResponseFactory. ResponseFactory's json function has the following signature:

public function json($data = [], $status = 200, array $headers = [], $options = 0)

Calling json() will create a new instance of Illuminate\Http\JsonResponse, which will be the class responsible for running json_encode for your data. Inside the setData function in JsonResponse, your array will be encoded with the $options provided on the response()->json(...) call:

 json_encode($data, $this->jsonOptions);

As you can see on the documentation on php.net for the json_encode function and the documentation on php.net for the json_encode Predefined Constants, JSON_UNESCAPED_UNICODE will encode multibyte Unicode characters literally (default is to escape as \uXXXX).

It is important to note that JSON_UNESCAPED_UNICODE has only been supported since PHP 5.4.0, so make sure you are running 5.4.0 or newer to use this.

like image 83
Tim Groeneveld Avatar answered Sep 22 '22 09:09

Tim Groeneveld