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,而不是从,保存您传输的数据.
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)
小智 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)
归档时间: |
|
查看次数: |
85367 次 |
最近记录: |