Home>Article>Backend Development> What should I do if the characters are garbled after php writes it into a txt file?
Solution to the problem of garbled characters after php writes a txt file: 1. Create a PHP sample file; 2. Create "function file_utf8($filepath){...}"; 3. Save the txt file as "UTF-8" will do.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
After php writes the txt file, the characters are garbled What should I do?
php always has problems processing Chinese encoding. This is an encoding problem. You can save the txt file as UTF-8 encoding and then process it;
Reference is as follows:
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'=>'打开文件失败'); } }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What should I do if the characters are garbled after php writes it into a txt file?. For more information, please follow other related articles on the PHP Chinese website!