我有一个将多个文件组合成一个文件的脚本,当其中一个文件使用UTF8编码时,它就会中断。我认为我应该在读取文件时使用utf8_decode()
函数,但我不知道如何区分哪些文件需要解码。
我的代码基本上是:
$output = '';
foreach ($files as $filename) {
$output .= file_get_contents($filename) . "\n";
}
file_put_contents('combined.txt', $output);
目前,在UTF8文件的开头,它在输出中添加以下字符:
发布于 2013-02-27 06:24:55
为了确保输出是UTF-8,不管是哪种类型的输入,我都使用这个check
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!
发布于 2014-04-22 23:34:50
这是我的解决方案,效果很好:
//check string strict for encoding out of list of supported encodings
$enc = mb_detect_encoding($str, mb_list_encodings(), true);
if ($enc===false){
//could not detect encoding
}
else if ($enc!=="UTF-8"){
$str = mb_convert_encoding($str, "UTF-8", $enc);
}
else {
//UTF-8 detected
}
发布于 2015-09-17 17:53:01
对于Linux服务器,我使用以下命令:
$file = 'your/file.ext'
exec( "from=`file -bi $file | awk -F'=' '{print $2 }'` && iconv -f \$from -t utf-8 $file -o $file" );
https://stackoverflow.com/questions/505562
复制相似问题