如果生成的 PHP 文件中的中文是乱码的,可能是因为在远程调用 HTTPS 网址时未正确设置字符编码。

你可以指定字符编码为 UTF-8,如下所示:

$url = 'https://example.com'; // 远程 HTTPS 网址
$content = file_get_contents($url); // 获取网页内容
$content = iconv('gb2312', 'utf-8//IGNORE', $content); // 转换编码为 UTF-8
file_put_contents('output.php', $content); // 生成 PHP 文件

在上述代码中,使用了 iconv() 函数将远程网页内容从 GB2312 编码转换为 UTF-8 编码。这样,生成的 PHP 文件中的中文内容就可以正常显示了。

请注意,如果远程 HTTPS 网址的内容本身就是 UTF-8 编码的,则无需进行编码转换。你可以使用以下代码来自动检测网页内容的编码:

function detect_encoding($string) {
    $list = array('utf-8', 'gb2312', 'gbk', 'big5', 'cp936');
    foreach ($list as $item) {
        $sample = iconv($item, $item, $string);
        if (md5($sample) == md5($string)) {
            return $item;
        }
    }
    return null;
}

$url = 'https://example.com'; // 远程 HTTPS 网址
$content = file_get_contents($url); // 获取网页内容
$encoding = detect_encoding($content); // 检测编码
if ($encoding !== 'utf-8') {
    $content = iconv($encoding, 'utf-8//IGNORE', $content); // 转换编码为 UTF-8
}
file_put_contents('output.php', $content); // 生成 PHP 文件

在上述代码中,使用了 detect_encoding() 函数来自动检测网页内容的编码。如果网页内容的编码不是 UTF-8,则使用 iconv() 函数将其转换为 UTF-8 编码。

PHP 远程调用 HTTPS 网址内容,解决生成文件中文乱码问题

原文地址: https://www.cveoy.top/t/topic/lDh9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录