php去掉文件UTF-8的BOM头

最近解析csv文件时第一列解析不出来,经过研究发现是文件BOM的问题

可以用以下代码去掉BOM

 1 function checkBOMAndRemove($filename){
 2     $contents = file_get_contents($filename);
 3     $charset[1] = substr($contents, 0, 1);
 4     $charset[2] = substr($contents, 1, 1);
 5     $charset[3] = substr($contents, 2, 1);
 6     if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
 7         $rest = substr($contents, 3);
 8         rewrite($filename, $rest);
 9         return true;
10     } else
11         return false;
12 }
13 
14 
15 function rewrite($filename, $data){
16     $filenum = fopen($filename, "w");
17     flock($filenum, LOCK_EX);
18     fwrite($filenum, $data);
19     fclose($filenum);
20 }

 

posted @ 2020-07-09 21:47  烟云的追寻  阅读(413)  评论(0)    收藏  举报

越学习越感觉无知!