fossar/guzzle-transcoder

Guzzle 插件,将响应转换为 UTF-8 编码

0.3.0 2023-03-07 23:13 UTC

This package is auto-updated.

Last update: 2024-09-15 23:29:39 UTC


README

Packagist Version

此包提供了一个 Guzzle 6/7 中间件,透明地将 Guzzle 获取的文档从其原生编码转换为 UTF-8(或任何其他指定的编码)。它支持以下功能

  • Content-Type HTTP 头部检测字符集。
  • 从 HTML 文档中的 meta 元素 检测字符集。
  • 从 RSS 和其他 XML 文档中的 XML 声明 检测字符集。
  • 根据目标编码更新 Response 对象中的 Content-Type 头部。
  • 根据目标编码更新 Response 主体中的元数据(默认不启用)。

安装

建议使用 Composer 安装库

composer require fossar/guzzle-transcoder

用法

基本示例

use Fossar\GuzzleTranscoder\GuzzleTranscoder;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
$stack->push(new GuzzleTranscoder);
$client = new Client(['handler' => $stack]);

$url = 'https://www.myseosolution.de/scripts/encoding-test.php?enc=iso'; // request website with iso-8859-1 encoding
$req = $client->get($url);
echo $req->getBody();

完整示例

use Fossar\GuzzleTranscoder\GuzzleTranscoder;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
$stack->push(new GuzzleTranscoder([
	'targetEncoding' => 'windows-1252',
	// Swap the default settings:
	'replaceHeaders' => false,
	'replaceContent' => true,
]));
$client = new Client(['handler' => $stack]);

$url = 'https://www.myseosolution.de/scripts/encoding-test.php?enc=iso'; // request website with iso-8859-1 encoding
$req = $client->get($url);
echo $req->getHeaderLine('Content-Type') . "\n"; // HTTP header will remain unchanged
echo $req->getBody();

致谢

它主要基于 Pascal Landau 的 guzzle-auto-charset-encoding-subscriberweb-utility 库。

我们使用 Transcoder 库。这允许我们在 mbstring 不可用或它不支持某个编码时回退到 iconv

源代码在 MIT 许可证 下可用