今天在項目中發現,客戶端在使用ajax得到返回值時,無法匹配字符串。總是報錯,打開頁面接口發現,頁面的頭部出現了的字符(BOM頭),找到問題了,那么直接用代碼清除掉即可。
php隱形字符解釋如下:
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、接notopad++ 保存為無dom格式(格式->轉為UTF-8 無dom格式),適合文件少的情況。
2、文件比較多,又想偷懶下,使用下列方法來實現(親測可用)。將一下代碼保存為a.php文件放到根目錄下,執行一下,即可自動完成轉換。
代碼如下:
- <?php
- // 設定你要清除BOM的根目錄(會自動掃描所有子目錄和文件)
- $HOME = dirname(__FILE__);
- // 如果是Windows系統,修改為:$WIN = 1;
- $WIN = 0;
- ?>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>UTF8 BOM 清除器</title>
- <style>
- body { font-size: 10px; font-family: Arial, Helvetica, sans-serif; background: #FFF; color: #000; }
- .FOUND { color: #F30; font-size: 14px; font-weight: bold; }
- </style>
- </head>
- <body>
- <?php
- $BOMBED = array();
- RecursiveFolder($HOME);
- echo '<h2>These files had UTF8 BOM, but i cleaned them:</h2><p class="FOUND">';
- foreach ($BOMBED as $utf) { echo $utf ."<br />\n"; }
- echo '</p>';
- // 遞歸掃描
- function RecursiveFolder($sHOME) {
- global $BOMBED, $WIN;
- $win32 = ($WIN == 1) ? "\\" : "/";
- $folder = dir($sHOME);
- $foundfolders = array();
- while ($file = $folder->read()) {
- if($file != "." and $file != "..") {
- if(filetype($sHOME . $win32 . $file) == "dir"){
- $foundfolders[count($foundfolders)] = $sHOME . $win32 . $file;
- } else {
- $content = file_get_contents($sHOME . $win32 . $file);
- $BOM = SearchBOM($content);
- if ($BOM) {
- $BOMBED[count($BOMBED)] = $sHOME . $win32 . $file;
- // 移出BOM信息
- $content = substr($content,3);
- // 寫回到原始文件
- file_put_contents($sHOME . $win32 . $file, $content);
- }
- }
- }
- }
- $folder->close();
- if(count($foundfolders) > 0) {
- foreach ($foundfolders as $folder) {
- RecursiveFolder($folder, $win32);
- }
- }
- }
- // 搜索當前文件是否有BOM
- function SearchBOM($string) {
- if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
- return false;
- }
- ?>
- </body>
- </html>
如果您對上面的內容還有補充,請在文章下評論或者給我
[留言]。謝謝!