如何在 Laravel 控制器 json 响应中正确使用utf8_decode



我正在努力使用Laravel JSON响应。

我正在尝试做的是向Laravel控制器创建一个CURL请求。

所以这是 CURL 代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://dev.laravel/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

。这是控制器代码:

$data = array(
    'code' => ($this->code ? $this->code : 0),
    'message' => 'àèìòù',
    'data' => ''
);
return response()->json($data);

问题是 消息强调 .但是,如果我只返回一个字符串并utf8_decode($output)重音工作,下面是一个例子:

// curl
echo utf8_decode($output);
// laravel controller
return 'àèìòù';

[更新]

另一个不起作用的例子:

$response = array(
    'code' => 200,
    'message' => 'àèìòù',
    'data' => array()
);
return response()->json($response, 200, [], JSON_UNESCAPED_UNICODE);
{"code":200,"message":"à èìòù","data":[]} // result

在幕后,Laravel正在使用json_encode .尝试使用 JSON_UNESCAPED_UNICODE -选项:

response()->json($data, 200, [], JSON_UNESCAPED_UNICODE);

JSON_UNESCAPED_UNICODE

从字面上对多字节 Unicode 字符进行编码(默认为转义为 \uXXXX)。从 PHP 5.4.0 开始可用。

请参阅 http://php.net/manual/en/json.constants.php 。

我以前遇到过这个问题,但是当我使用 json_encode() 函数时,它工作正常:

return json_encode($data);

这是我所做的:

json_encode($data, JSON_UNESCAPED_UNICODE);

无论如何,在客户端,我必须使用:

utf8_decode($response['message']);

PHP 8+ 允许命名参数

return response()->json($data, options: JSON_UNESCAPED_UNICODE);

最新更新