[英]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. 问题是我不能在response()->json()
方法中使用任何俄语符号。 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. 此外,我的所有文件都已转换为没有BOM的UTF-8。 I've added the default character set to the .htaccess file( AddDefaultCharset utf-8
) as well. 我已经将默认字符集添加到.htaccess文件( AddDefaultCharset utf-8
)。
But, I still get the wrong response like here: 但是,我仍然得到像这里错误的回应:
{"users":"\u0442\u0435\u0441\u0442"}
The response that you are getting: 你得到的回应:
{"users":"\u0442\u0435\u0441\u0442"}
is valid JSON! 是有效的JSON!
That being said, if you don't want to encode the UTF-8 characters, you can simply just do this: 话虽这么说,如果你不想编码UTF-8字符,你可以简单地这样做:
$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":"тест"}
Calling the response()
helper will create an instance of Illuminate\\Routing\\ResponseFactory
. 调用response()
帮助器将创建Illuminate\\Routing\\ResponseFactory
的实例。 ResponseFactory
's json
function has the following signature: ResponseFactory
的json
函数具有以下签名:
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. 调用json()
将创建一个新的Illuminate\\Http\\JsonResponse
实例,它将是负责为您的数据运行json_encode
的类。 Inside the setData
function in JsonResponse
, your array will be encoded with the $options
provided on the response()->json(...)
call: 在JsonResponse
的setData
函数内,您的数组将使用response()->json(...)
调用提供的$options
进行编码:
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). 正如你在php.net上关于json_encode
函数的文档和php.net上关于json_encode
预定义常量的文档所看到的, JSON_UNESCAPED_UNICODE
将逐字编码多字节Unicode字符(默认是以\\ 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. 值得注意的是,自PHP 5.4.0起, JSON_UNESCAPED_UNICODE
仅受支持,因此请确保运行5.4.0或更高版本以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.