简体   繁体   English

HTML 特殊字符和表情符号在 Laravel 网页上显示不正确

[英]HTML Special Characters and Emojis Showing up Incorrectly on Laravel Webpage

I am likely doing something silly and thought this would be pretty straightforward.我可能会做一些愚蠢的事情,并认为这很简单。 I am pulling data from an external API and storing it right into the database via Eloquent model's I am creating/saving.我正在从外部 API 中提取数据,并通过我正在创建/保存的 Eloquent 模型将其直接存储到数据库中。

The data saved into the database field looks like this: I Can't Believe It's A - The field is using utf8mb4_unicode_ci collation.保存到数据库字段中的数据如下所示: I Can't Believe It's A - The field is using utf8mb4_unicode_ci

My webpage has the following meta data:我的网页有以下元数据:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

And I am displaying it via my Laravel blade template like so:我通过我的 Laravel 刀片模板显示它,如下所示:

<td>{{ $company->type->name }}</td>

I am a bit confused what I am doing wrong here?我有点困惑我在这里做错了什么? From the documentation and other stackoverflow questions I appear to be doing it correctly.从文档和其他stackoverflow问题来看,我似乎做得正确。 My config/database.php has the following:我的config/database.php具有以下内容:

        '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' => 'InnoDB',
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

I believe this is all correct.我相信这一切都是正确的。 Is there something I am missing here?我在这里缺少什么吗? Switching to use the unescaped {!! !!}切换到使用未转义的{!! !!} {!! !!} seems to result in the content still being displayed the same. {!! !!}似乎导致内容仍然显示相同。 I am using Laravel v7.13.0我正在使用 Laravel v7.13.0

Also Google Chrome reports it is UTF-8 rendered:谷歌浏览器也报告它是 UTF-8 渲染的:

> document.characterSet
"UTF-8"

Edit:编辑:

Here is an example of getting the response and what the returned JSON name looks like:这是获取响应的示例以及返回的 JSON 名称的样子:

>>> $response = Http::withOptions(
            [
                'verify' => false,
                'base_uri' => config('custom.torn_api_base'),
                'timeout' => 5.0
            ]
        )->get(
            "company/79831",
            [
                'selections' => 'profile',
                'key' => config('custom.torn_api_key')
            ]
        );
=> Illuminate\Http\Client\Response {#3393
     +"cookies": GuzzleHttp\Cookie\CookieJar {#3379},
     +"transferStats": GuzzleHttp\TransferStats {#3418},
   }

>>> $response->json()['company']['name'];
=> "👾 Button Mashers™"

^ You can see above their API is giving me the same string with the UTF-8 encoding that would be used on their website. ^ 你可以在上面看到他们的 API 给了我与 UTF-8 编码相同的字符串,这将在他们的网站上使用。

Here is me creating and saving the model to the database:这是我创建 model 并将其保存到数据库中:

            $company = Company::updateOrCreate(
                [
                    'id' => $tornPlayerData['job']['company_id']
                ],
                [
                    'name' => $tornPlayerData['job']['company_name'],
                    'player_id' => $this->player->id,
                    'isOwner' => true
                ]
            );

I also am logging the response and here is what one of the lines with an Emoji looks like:我也在记录响应,下面是带有表情符号的行之一:

Log::info("Updating company '{$company->name}'' now", ['company' => $company]);

laravel.log│[2020-06-22 00:43:52] staging.INFO: Updating company '&#128126; Button Mashers&#8482;'' now {"company":{"App\\Company":{"id":79831,"name":"&#128126; Button Mashers&#8482;","player_id":2141091,"updated_at":"2020-06-22T04:43:52.000000Z","created_at":"2020-06-22T04:43:52.000000Z"}}}

Edit 2: I just manually copied and pasted the Tinker output of Button Mashers™ to name in the associated database row.编辑 2:我只是手动复制并粘贴了Button Mashers™的 Tinker output 以在关联的数据库行中name Now the website displays that manually adjusted one properly.现在网站显示手动调整了一个正确的。 So it seems Laravel is doing something weird to the data from the API when it is storing it and I am unsure why that would be.因此,Laravel 在存储 API 的数据时似乎对它做了一些奇怪的事情,我不确定为什么会这样。

Edit 3:编辑3:

Using the HEX query as the user asked in the answer.使用HEX查询作为用户在答案中提出的问题。

SELECT id,name,HEX(name) FROM `companies` WHERE id=60335

(60335, 'Pokey&#039;s Play House!', '506F6B657926233033393B7320506C617920486F75736521');

(60335, '&#039;', '26233033393B');

The second result is with me modifying the Pokey&#039;s Play House!第二个结果是我修改了Pokey&#039;s Play House! to just &#039;只是&#039; so you can see the result of just the apostrophe.所以你可以看到只有撇号的结果。

Edit 4:编辑4:

The blade template:刀片模板:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Company Directory</title>

        <!-- Fonts -->
{{--        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">--}}

        <!-- Styles -->
          ** Snipped some minor CSS away from here **
        </style>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">

        <!-- Scripts -->

        <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
        <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
        <script type="text/javascript" charset="utf8">
            **removed some datatables code from here for this paste**
        </script>

    </head>
    <body>
        <table id='directory-table' class='display'>
            <thead>
                <tr>
                    <th>Player Name</th>
                    <th>Company Name</th>
                    <th>Type</th>
                    <th>Rank</th>
                    <th>Positions</th>
                </tr>
            </thead>
            <tbody>
                @forelse ($companies as $company)
                    <tr>
                        <td>
                            <a href='https://www.example.
net/profiles.php?XID={{ $company->player->id }}'>
                                {{ $company->player->name }}
                            </a>
                        </td>
                        <td>
                            <a href='https://www.example.net/joblist.php#/p=corpinfo&userID={{ $company->id }}'>
                                {{ $company->name }}
                            </a>
                        </td>
                        <td>{{ $company->type->name }}</td> //THIS IS THE PROBLEM STRING HERE BEING OUTPUTTED
                        <td> {{ $company->rank }}</td>
                        <td> {{ $company->hired_employees }}/{{ $company->max_employees }}</td>
                    </tr>
                @empty
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </body>
</html>

In your blade, try printing using the following statements:在您的刀片中,尝试使用以下语句进行打印:

{!! html_entity_decode($company->name) !!}

OR或者

<?php echo $company->name; ?>

Official docs on printing data in blade .关于在刀片中打印数据的官方文档。

"HTML entities" (such as &#039; ) are useful for web pages, but should not be how you store things into a database. “HTML 实体”(例如&#039; )对于 web 页面很有用,但不应该是您将内容存储到数据库中的方式。

It may be that you converted to entities twice, once before storing the data, once while displaying on a web page.可能是您转换为实体两次,一次是在存储数据之前,一次是在 web 页面上显示时。 To further diagnose the issue, get SELECT HEX(..)... of the string.要进一步诊断问题,请获取字符串的SELECT HEX(..)...

It seems like an encoding problem to me.对我来说,这似乎是一个编码问题。

You need to open AppServiceProvider and add below code in boot method :您需要打开AppServiceProvider并在boot method中添加以下代码:

Blade::setEchoFormat('e(utf8_encode(%s))');

Hope this works for you!!希望这对你有用!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM