+ -

php写入txt文件后字符乱码怎么办

时间:2021-09-24

来源:互联网

在手机上看
手机扫描阅读

今天PHP爱好者给大家带来php写入txt文件后字符乱码的解决办法:1、创建一个PHP示例文件;2、创建“function file_utf8($filepath){...}”;3、将txt文件另存为“UTF-8”即可。希望对大家有所帮助。

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php写入txt文件后字符乱码怎么办?

php处理中文编码老是有问题,这是编码的问题,可以将txt文件另存为UTF-8的编码再处理;

  参考如下:

function file_utf8($filepath){
    $f_contents= file_get_contents($filepath);
     
    $encoding = mb_detect_encoding($f_contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
 
    $content_u="";
    $handle=fopen($filepath,"r");
    if ($handle){
        while (!feof($handle)) {
            $buffer= fgets($handle);
            if ($encoding != false) {
                if (mb_detect_encoding($buffer)!='UTF-8'){
                    $buffer = iconv($encoding, 'UTF-8', $buffer);
                }
            }else{
                    $buffer = mb_convert_encoding ( $buffer, 'UTF-8','Unicode');
            }
            $content_u.=$buffer;
        }
        fclose($handle);
        return $info=array('status'=>1,'message'=>$content_u);
    }else{
        return $info=array('status'=>0,'message'=>'打开文件失败');
    }
}

以上就是php写入txt文件后字符乱码怎么办的详细内容,更多请关注php爱好者其它相关文章!