Laravel Blade 组件 - UTF-8 编码问题

Laravel Blade Component - UTF-8 Encoding issue

我目前正在开发 Laravel 8 版本的应用程序。我构建了一个名为 input-group 的组件,它会导致我不理解的编码问题。该组件的代码如下所示:

<div class="form-group" {{ isset($attributes['style']) ? $attributes->merge(['style' => $attributes['style']]) : null }}>
    @if(isset($attributes['label']))
        <label for="{{ $attributes['id'] }}">{{ $attributes['label'] }}</label>
        <input type="text" 
               value="{{ isset($attributes['value']) ? $attributes['value'] : null }}" 
               class="form-control form-control-sm" 
               name="{{ $attributes['name'] }}" 
               id="{{ $attributes['id'] }}" 
               placeholder="{{ isset($attributes['placeholder']) ? $attributes['placeholder'] : null }}">
    @else 
        <input style="width:100%;" type="text" value="{{ isset($attributes['value']) ? $attributes['value'] : null }}" class="form-control form-control-sm" name="{{ $attributes['name'] }}" id="{{ $attributes['id'] }}" placeholder="{{ isset($attributes['placeholder']) ? $attributes['placeholder'] : null }}">
    @endif
  </div>

这是我注入 value 属性的数据 => Inspecteur de l'Education Nationale

这是我在 <input> 中得到的输出:Inspecteur de l&#039;Education Nationale

我明确指出我的数据库(使用 mySQL)具有 Laravel 默认编码 utf8mb4_unicode_ci。我用来获取这些数据的请求是一个经典的 Eloquent 请求(我不操作编码)

mysql 驱动程序的配置如下所示:

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

使用{!! !!}代替{{ }}

即:

value="{!! isset($attributes['value']) ? $attributes['value'] : null !!}"

Displaying Unescaped Data

By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks.

{!! !!} 可以,但我不会在这里使用它。

特别是如果您呈现的值有可能被用户设置,因为它是未转义的。这是一个潜在的漏洞,您让自己容易受到 XSS 攻击。

您可以改为:

{{ html_entity_decode($value) }},您仍然可以获得 blade 帮助防止 XSS 攻击的好处。

您可以在此处阅读有关此功能的更多信息:https://www.php.net/manual/en/function.html-entity-decode.php