当前位置: 移动技术网 > IT编程>开发语言>PHP > php中隐形字符65279(utf-8的BOM头)问题

php中隐形字符65279(utf-8的BOM头)问题

2019年03月19日  | 移动技术网IT编程  | 我要评论

武林风一龙最新比赛,林西一中吧,长江有色金属网价格

今天在csdn看到一个php输出空白隐形字符65279的问题,在网上找了下,发下这个65279字符是php用来标记文件是utf-8编码的,输出的时候会一起输出到客户端,导致客户端如果使用ajax得到返回值时,无法匹配字符串。

php隐形字符65279解释如下:

utf-8 编码的文件可以分为无 bom 和 bom 两种格式。

何谓bom?

  "ef bb bf" 这三个字节就叫bom,全称是"byte order mard"。在utf8文件中常用bom来表明这个文件是utf-8文件,而bom的本意是在utf16中用。

  utf-8文件在php中输出的时候bom是会被输出的,所以要在php中使用utf-8,必须要是使用不带bom头的utf-8文件。

  常用的文本编辑软件对utf-8文件保存的支持方式并不一样,使用的时候要特别留意。

例如:

1、使用ultraedit时,另存时会有“utf-8”和“utf-8 - 无bom”两种选择。
2、 window的记事本保存的是带bom的。
3、editplus软件不同版本对utf-8的保存支持不一样,例如:2.31版本保存的是不带bom的,2.11版本保存的是带bom的。

把utf-8文件头去掉的办法:

1、使用ultraedit另存,选择“utf-8 - 无bom”
2、一个很有用的php程序,放在站点根目录下运行,会把目录下全部utf-8文件的bom头去掉,代码如下:

//remove the utf-8 boms 
 //by magicbug at gmail dot com 
  
 if (isset($_get['dir'])){ //config the basedir 
   $basedir=$_get['dir']; 
 }else{ 
   $basedir = '.'; 
 } 
  
 $auto = 1; 
  
 checkdir($basedir); 
  
 function checkdir($basedir){ 
   if ($dh = opendir($basedir)) { 
     while (($file = readdir($dh)) !== false) { 
       if ($file != '.' && $file != '..'){ 
         if (!is_dir($basedir."/".$file)) { 
           echo "filename
 $basedir/$file ".checkbom("$basedir/$file")." <br>"; 
         }else{ 
           $dirname = $basedir."/".$file; 
           checkdir($dirname); 
         } 
       } 
     } 
   closedir($dh); 
   } 
 } 
  
 function checkbom ($filename) { 
   global $auto; 
   $contents = file_get_contents($filename); 
   $charset[1] = substr($contents, 0, 1); 
   $charset[2] = substr($contents, 1, 1); 
   $charset[3] = substr($contents, 2, 1); 
   if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) { 
     if ($auto == 1) { 
       $rest = substr($contents, 3); 
       rewrite ($filename, $rest); 
       return ("<font color=red>bom found, automatically removed.</font>"); 
     } else { 
       return ("<font color=red>bom found.</font>"); 
     } 
   } 
   else return ("bom not found."); 
 } 
  
 function rewrite ($filename, $data) {
   $filenum = fopen($filename, "w"); 
   flock($filenum, lock_ex); 
   fwrite($filenum, $data); 
   fclose($filenum); 
} 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网