這篇文章主要為大家展示了“php bom如何去掉”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“php bom如何去掉”這篇文章吧。
去掉php bom的方法:1、找到PHP根目錄;2、將“function checkBOM($filename){...}”等代碼放到根目錄下,并通過瀏覽器運行訪問即可。
本文操作環境:Windows7系統,PHP7.4版,Dell G3電腦。
PHP去除BOM簡單的方法
/* +------------------------------------------------------------------------------------------- + Title : 去掉BOM頭方法 + Author : hello_sgw + Version : V1.0.0.1 + Initial-Time : 2017-08-12 15:18 + Last-time : 2017-08-12 16:01 + Desc : +------------------------------------------------------------------------------------------- */
自己在調用接口時候,因為用到了對方提供的封裝方法,在輸出一組數據時候一直顯示錯誤,最后想到可能對方給的方法里面含有編碼問題(具有BOM頭),所以上網搜索到一個檢測BOM的方法并且可以去除重新生成新文件,運用之后就能正常顯示數據了。
什么是BOM頭?
BOM --Byte Order Mark,中文名譯作“字節順序標記”,在utf-8編碼文件中BOM在文件頭部,占用三個字節,用來標示該文件屬于utf-8編碼,
現在已經有很多軟件識別bom頭,但是還有些不能識別bom頭,比如PHP就不能識別bom頭,這也是用記事本編輯utf-8編碼后執行就會出錯的原因了。
解決方法:
# 這里代碼為PHP方式去除當前目錄及字目錄所有文件BOM信息,只要將此代碼文件放到根目錄下,然后瀏覽器運行訪問就可以了 <?php if (isset($_GET['dir'])) { //設置文件目錄 $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); }
以上是“php bom如何去掉”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。