gpt4 book ai didi

php - Goutte/Guzzle 可以强制进入 UTF-8 模式吗?

转载 作者:可可西里 更新时间:2023-11-01 13:03:35 25 4
gpt4 key购买 nike

我正在使用 Goutte 从 UTF-8 网站抓取数据,它在内部使用 Guzzle。该站点声明了一个 UTF-8 元标记,因此:

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

但是,内容类型 header 是这样的:

Content-Type: text/html

而不是:

Content-Type: text/html; charset=utf-8

因此,当我抓取时,Goutte 并没有发现它是 UTF-8,而是错误地抓取了数据。远程站点不在我的控制之下,所以我无法解决那里的问题!这是一组用于复制问题的脚本。一、刮刀:

<?php

require_once realpath(__DIR__ . '/..') . '/vendor/goutte/goutte.phar';

$url = 'http://crawler-tests.local/utf-8.php';
use Goutte\Client;

$client = new Client();
$crawler = $client->request('get', $url);
$text = $crawler->text();
echo 'Whole page: ' . $text . "\n";

现在是放置在网络服务器上的测试页面:

<?php
// Correct
#header('Content-Type: text/html; charset=utf-8');

// Incorrect
header('Content-Type: text/html');
?>
<!DOCTYPE html>
<html>
<head>
<title>UTF-8 test</title>
<meta charset="utf-8" />
</head>
<body>
<p>When the Content-Header header is incomplete, the pound sign breaks:

£15,216</p>
</body>
</html>

这是 Goutte 测试的输出:

Whole page: UTF-8 test When the Content-Header header is incomplete, the pound sign breaks: £15,216

正如您从上一个脚本中的注释中看到的那样,在 header 中正确声明字符集可以解决问题。我在古特四处寻找,看看是否有任何看起来会强制字符集的东西,但无济于事。有什么想法吗?

最佳答案

问题实际上出在 symfony/browser-kit 和 symfony/domcrawler 上。 browserkit 的 Client does not examine the HTML meta tags仅确定字符集、内容类型 header 。当response body交给domcrawler时,就是treated作为the default charset ISO-8859-1 .在检查元标记后,应该恢复决定并重建 DomDocument,但这从未发生。

简单的解决方法是用 utf8_decode() 包装 $crawler->text():

$text = utf8_decode($crawler->text());

如果输入是 UTF-8,这会起作用。我想对于其他编码可以用 iconv() 实现类似的东西或者。但是,每次调用 text() 时都必须记住这样做。

一种更通用的方法是让 Domcrawler 相信它处理的是 UTF-8。为此,我想出了一个 Guzzle 插件,它会覆盖(或添加)内容类型响应 header 中的字符集。您可以在 https://gist.github.com/pschultz/6554265 找到它.用法是这样的:

<?php

use Goutte\Client;


$plugin = new ForceCharsetPlugin();
$plugin->setForcedCharset('utf-8');

$client = new Client();
$client->getClient()->addSubscriber($plugin);
$crawler = $client->request('get', $url);

echo $crawler->text();

关于php - Goutte/Guzzle 可以强制进入 UTF-8 模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18782332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com