設為首頁收藏本站

 取回密碼
 註冊
搜尋
熱搜: Redump discuz
檢視: 439|回覆: 0

【轉貼】 php中隱形字符65279(utf-8的BOM頭)

[複製連結]
匿名
匿名  發表於 2021年4月22日 21:49:20 |閱讀模式
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頭去掉,代碼如下:

<?php
//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); 
}
?>
懶得打字嗎?讓本助手協助你 【使用進階編輯器請點選右方進階模式】
您需要登入後才可以回覆 登入 | 註冊

本版積分規則

手機版|Archiver|漁家小舖

GMT+8, 2024年3月29日 19:37 , Processed in 0.277938 second(s), 15 queries , Gzip On, Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回覆 返回頂端 返回清單