如何让 Laravel 在所有响应中指定我的字符集?

How do I get Laravel to specify my charset in all responses?

是的,我知道我应该使用 UTF-8,但我需要使用 windows-1252 字符集编码。

我知道我可以通过对基本 Synfony 响应进行硬编码来做到这一点 class Response.php,

$charset = $this->charset ?: 'windows-1252';

但这太丑了。

我无法从配置文件中找到设置它的位置。有帮助吗?

您可以在中间件中更改字符集:

<?php namespace App\Http\Middleware;

use Closure;

class SetCharset
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Content-Type', 'text/html; charset=windows-1252');

        return $response;
    }
}

只需确保您 return 的所有内容都采用正确的编码。

改进 仅当内容类型为 text/html 时才更改字符集。

<?php 

namespace App\Http\Middleware;

use Closure;

class SetCharset
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $contentType = $response->headers->get('Content-Type');
        if (strpos($contentType, 'text/html') !== false) {
            $response->header('Content-Type', 'text/html; charset=windows-1252');
        }

        return $response;
    }
}

将SetCharset.php放入app/Http/Middleware文件夹,然后修改app/Http/Kernel.php,在$middleware数组末尾添加class引用属性:

protected $middleware = [
    // ... Other middleware references
    \App\Http\Middleware\SetCharset::class,
];