Hugh's Blog

PHP 转换编码带 BOM 的问题

PHP 在转换文件编码时,如果遇到带有 BOM 头的话,会导致其他应用读取到的内容出现乱码,需要做单独的处理。

$content = file_get_contents('in.txt');

$encode = mb_detect_encoding($content, ['ASCII', 'GBK', 'GB2312', 'BIG5', 'UTF-8']);
if ($encode !== 'UTF-8') {
    $content = iconv($encode, 'UTF-8', $content);
}

// Check if has bom
$bom = pack("CCC", 0xef, 0xbb, 0xbf);
if (strncmp($content, $bom, 3) === 0) {
    $content = substr($content, 3);
}

file_put_contents('out.txt', $content);

在 Linux 下检测文件是否带 BOM 可以使用命令 hexdump -C in.txt,如果最开始出现 ef bb bf 的话,就是 UTF-8 with BOM 的编码。

00000000  ef bb bf 31 31 31                                 |...111|
00000006