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".
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; } } } }
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!