是否可以在 Lumen(by Laravel) 中使用西里尔符号?

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

问题是我无法在 response()->json() 方法中使用任何俄语符号。 我已经尝试过以下代码:

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');

我检查了默认编码:

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

此外,我的所有文件都已转换为无 BOM 的 UTF-8。我也将默认字符集添加到 .htaccess 文件 (AddDefaultCharset utf-8)。

但是,我仍然得到像这里这样的错误响应:

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

您得到的回复:

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

有效JSON!

也就是说,如果您不想对 UTF-8 字符进行编码,您可以简单地这样做:

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

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

输出将是

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

为什么这样做?

调用 response() 助手将创建 Illuminate\Routing\ResponseFactory 的实例。 ResponseFactoryjson 函数具有以下签名:

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

调用 json() 将创建一个新的 Illuminate\Http\JsonResponse 实例,它将成为 class 负责 运行 json_encode 您的数据。在 JsonResponse 中的 setData 函数内,您的数组将使用 response()->json(...) 调用中提供的 $options 进行编码:

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

正如您在 documentation on php.net for the json_encode function and the documentation on php.net for the json_encode Predefined Constants 中所见,JSON_UNESCAPED_UNICODE 将按字面意义编码多字节 Unicode 字符(默认转义为 \uXXXX)。

重要的是要注意 JSON_UNESCAPED_UNICODE 仅在 PHP 5.4.0 之后才受支持,因此请确保您是 运行 5.4.0 或更高版本才能使用它。