Anonymous 發表於 2021年4月22日 21:49:20

php中隱形字符65279(utf-8的BOM頭)

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 = substr($contents, 0, 1);
   $charset = substr($contents, 1, 1);
   $charset = substr($contents, 2, 1);
   if (ord($charset) == 239 && ord($charset) == 187 && ord($charset) == 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);
}
?>
頁: [1]
檢視完整版本: php中隱形字符65279(utf-8的BOM頭)