首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检测PHP中的文件编码

检测PHP中的文件编码
EN

Stack Overflow用户
提问于 2009-02-03 00:14:20
回答 7查看 102.5K关注 0票数 28

我有一个将多个文件组合成一个文件的脚本,当其中一个文件使用UTF8编码时,它就会中断。我认为我应该在读取文件时使用utf8_decode()函数,但我不知道如何区分哪些文件需要解码。

我的代码基本上是:

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

目前,在UTF8文件的开头,它在输出中添加以下字符:

EN

回答 7

Stack Overflow用户

发布于 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!
票数 26
EN

Stack Overflow用户

发布于 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
}
票数 3
EN

Stack Overflow用户

发布于 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" );
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/505562

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档