Can I use Cyrillic characters in Lumen (Laravel)?

The problem is that I cannot use any Russian characters in the response()->json() method. I have 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 checked the default encoding:

 mb_detect_encoding(''); // returns 'UTF-8' 

In addition, all my files were converter to UTF-8 without specification. I added the default character set to the .htaccess file ( AddDefaultCharset utf-8 ).

But I still get the wrong answer, like here:

 {"users":"\u0442\u0435\u0441\u0442"} 
+5
source share
1 answer

The answer you get:

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

valid JSON!

If you do not want to encode UTF-8 characters, you can simply do this:

  $data = [ 'users' => '' ]; $headers = [ 'Content-Type' => 'application/json; charset=utf-8' ]; return response()->json($data, 200, $headers, JSON_UNESCAPED_UNICODE); 

Then the output will be

  {"users":""} 

Why does it work?

Calling the response() helper will instantiate Illuminate\Routing\ResponseFactory . The ResponseFactory 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 using the $options provided when calling response()->json(...) :

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

As you can see in the JSON_UNESCAPED_UNICODE documentation for the json_encode function and the json_encode documentation for json_encode Predefined Constants , JSON_UNESCAPED_UNICODE will encode multibyte Unicode characters literally (by default, execute the \ uXXXX command).

It is important to note that JSON_UNESCAPED_UNICODE is only supported with PHP 5.4.0, so make sure you use 5.4.0 or later to use this.

+7
source

Source: https://habr.com/ru/post/1237190/


All Articles