在PHP中检测文件编码

nic*_*ckf 24 php utf-8 character-encoding

我有一个脚本,它将多个文件合并为一个,当其中一个文件具有UTF8编码时,它会中断.我认为我应该utf8_decode()在读取文件时使用该函数,但我不知道如何判断哪个需要解码.

我的代码基本上是:

$output = '';
foreach ($files as $filename) {
    $output .= file_get_contents($filename) . "\n";
}
file_put_contents('combined.txt', $output);
Run Code Online (Sandbox Code Playgroud)

目前,在UTF8文件的开头,它在输出中添加了这些字符: 

Ben*_*ank 29

尝试使用该mb_detect_encoding功能.此函数将检查您的字符串并尝试"猜测"其编码是什么.然后,您可以根据需要进行转换.作为brulak建议,不过,你可能会更好过转换 UTF-8,而不是,保存您传输的数据.

  • mb_detect_encoding()无法正确检测文本中的编码更改。因此,我脚本第2行中的解决方法:/sf/answers/1057041471/ (2认同)

pow*_*tac 21

为了确保输出是UTF-8,无论输入是什么类型,我都使用此检查:

if(!mb_check_encoding($output, 'UTF-8')
    OR !($output === mb_convert_encoding(mb_convert_encoding($output, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {

    $output = mb_convert_encoding($content, 'UTF-8', 'pass'); 
}

// $output is now safely converted to UTF-8!
Run Code Online (Sandbox Code Playgroud)

  • 第二个`mb_convert_encoding`调用中的`$ content`也不应该是'$ output`吗?否则,`$ content`来自哪里? (2认同)
  • 如果有人想知道"pass"=>如果设置了"pass",则不执行字符编码转换.http://php.net/manual/en/mbstring.supported-encodings.php (2认同)

小智 17

mb_detect_encoding功能应该是你的最后选择.这可能会返回错误的编码.Linux命令file -i /path/myfile.txt运行良好.在PHP中,您可以使用:

function _detectFileEncoding($filepath) {
    // VALIDATE $filepath !!!
    $output = array();
    exec('file -i ' . $filepath, $output);
    if (isset($output[0])){
        $ex = explode('charset=', $output[0]);
        return isset($ex[1]) ? $ex[1] : null;
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

  • 这会在 Windows 10 平台上工作吗?或者如果不是,我应该改变什么? (3认同)