What should I do if the txt read by php is garbled?

藏色散人
Release: 2023-03-02 13:12:02
Original
3479 people have browsed it

The solution to the problem that php reads txt with garbled characters: first use the "file_get_contents" function to read the entire file into a string; then get the encoding method of the file; then open the file in read-only mode; finally use iconv can convert "$encoding" to "UTF-8".

What should I do if the txt read by php is garbled?

Solution to PHP reading TXT Chinese garbled characters

The code is as follows:

//$fname文件名称 if ($fname = $_FILES['nickname']['tmp_name']) { //file_get_contents() 函数把整个文件读入一个字符串中。 $contents = file_get_contents($fname); //获取文件的编码方式 $encoding = mb_detect_encoding($contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII')); $fp=fopen($fname,"r");//以只读的方式打开文件 $text = ""; $num = 0; if(!(feof($fp))) { $num++; $str = trim(fgets($fp)); if ($encoding != false) { //iconv ()将$encoding 转换成“UTF-8” $str = iconv($encoding, 'UTF-8', $str); if ($str != "" and $str != NULL) { $text = $str; } } else { $str = mb_convert_encoding ( $str, 'UTF-8','Unicode'); if ($str != "" and $str != NULL) { $text = $str; } } } while(!(feof($fp))) { $str = ''; $str = trim(fgets($fp)); if ($encoding != false) { $str = iconv($encoding, 'UTF-8', $str); if ($str != "" and $str != NULL) { $text = $text.",".$str; } } else { $str = mb_convert_encoding ( $str, 'UTF-8','Unicode'); if ($str != "" and $str != NULL) { $text = $text.",".$str; } } } }
Copy after login

More For more related knowledge, please visitPHP中文网!

The above is the detailed content of What should I do if the txt read by php is garbled?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!