因为业务上的需求,需要使用PHP读取一个TXT文件,但是在设计到中文的问题上,就遇到了恶心的乱码问题;
	首先查看一下TXT的编码格式有四种:ANSI、Unicode、Unicode Big Endian、UTF-8
	1、先是使用mb_detect_encoding($contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'))语句
	发现即使在其中增加了Unicode格式,已经无法获得文件的编码格式,但是对与ANSI和UTF-8格式倒是可以使用;
	2、于是针对这个问题,专门做了一个如下的转换:
	       $str = mb_convert_encoding ( $str, 'UTF-8','Unicode');
	       只是需要在前面加上一个编码格式的判断。
	完整代码如下:
					
  if ($fname = $_FILES['nickname']['tmp_name']) {
          //获取文件的编码方式
          $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) {
                  $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;
                  }
              }
          }
      }
				 | 
			
The End



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)