PHP / 输出文件编码 / 从 ANSI 更改为 UTF-8-BOM

问题描述 投票:0回答:1

有没有办法阻止PHP自动更改Excel文件的编码或设置编码?

已经尝试过:

ini_set('default_charset', 'ANSI');
ini_set('output_encoding', 'ANSI');
header('Content-Type: application/vnd.ms-excel; charset=ANSI');

使用“phpoffice/phpexcel”。如果我在服务器上保存构建的 Excel 文件,并在没有 PHP 的情况下下载保存的文件,则 NotePad++ 中该文件的编码为 ANSI,并且文件在 MS Excel 程序中正确打开。

但是如果我尝试通过 PHP 返回正确的文件:

readfile($file_path);
// OR directly write to output
$objWriter->save('php://output');

然后下载的 Excel 文件编码将为 UTF-8-BOM,最终 MS Excel 只显示该文件的奇怪符号。但我可以在 NotePad++ 中打开该文件并将编码更改为 ANSI,然后该文件可以在 MS Excel 中正确打开。

如何使用 PHP 将 Excel 文件返回给客户端而不自动更改该文件的编码?

php file encoding utf-8 ansi
1个回答
0
投票

感谢@CBroe使用PHP检测UTF BOM(字节顺序标记),在设置“附件”标头之前:

$has_bomed_files = false;
foreach (get_included_files() as $file_path)
{
    $str = file_get_contents($file_path);
    $bom = pack("CCC", 0xef, 0xbb, 0xbf);
    if (0 === strncmp($str, $bom, 3))
    {
        $has_bomed_files = true;
        print $file_path;
        print '<br>';
    }
}

if ($has_bomed_files)
    exit(__FILE__ . ":" . __LINE__);

发现 BOM 在一个类中,我删除了该 BOM,现在 PHP 返回正确的 Excel 文件。

© www.soinside.com 2019 - 2024. All rights reserved.