php中隐形字符65279(utf-8的BOM头)问题和fwrite写入文件bom头
?php中隐形字符65279(utf-8的BOM头)问题 今天在CSDN看到一个php输出空白隐形字符65279的问题,在网上找了下,发下这个65279字符是php用来标记文件是utf-8编码的,输出的时候会一起输出到客户端,导致客户端如果使用ajax得到返回值时,无法匹配字符串。 ? 1 //remove the utf-8 boms 2 //by magicbug at gmail dot com 3 4 if (isset($_GET['dir'])) { config the basedir 5 $basedir = $_GET['dir']; 6 } else { 7 $basedir = '.'; 8 } 9 10 $auto = 111 12 checkdir($basedir); 13 14 function checkdir() 15 { 16 if ($dh = opendir()) { 17 while (($file = readdir($dh)) !== FALSE) { 18 $file != '.' && $file != '..'19 if (!is_dir($basedir . "/" . $file20 echo "filename 21 $basedir/$file " . checkBOM("$file") . " <br>"22 } 23 $dirname = 24 checkdir($dirname25 } 26 } 27 } 28 closedir($dh29 } 30 31 32 function checkBOM($filename33 34 global $auto35 $contents = file_get_contents(36 $charset[1] = substr($contents,137 $charset[2] = 38 $charset[3] = 39 ord($charset[1]) == 239 && $charset[2]) == 187 && $charset[3]) == 19140 $auto == 141 $rest = 42 rewrite($filename,$rest43 return ("<font color=red>BOM found,automatically removed.</font>"44 } 45 return ("<font color=red>BOM found.</font>"46 47 } else return ("BOM Not Found."48 49 50 function rewrite($data51 52 $filenum = fopen(53 flock($filenum, LOCK_EX); 54 fwrite(55 fclose($filenum56 } ? ? //remove the utf-8 boms if (isset($_GET['dir'])) { //config the basedir $auto = 1; checkdir($basedir); function checkdir($basedir) function checkBOM($filename) function rewrite($filename,$data) ? fwrite写入文件bom头导致的乱码问题解决? ? php fwrite utf8 bom导致的乱码问题 ? 3 file_exists( 4 return 5 6 8 9 10 11 TRUE12 13 15 16 $msg = "你好n"17 如果默认编码不是utf8,先用函数utf8_encode将所需写入的数据变成UTF编码格式。 18 //$msg = utf8_encode($msg); 19 //$msg = iconv('gbk','utf-8',$msg); 20 21 $fileName = 'test'22 $filePath = './test.txt'23 $checkBom = checkBOM($filePath24 有bom的情况下"xEFxBBxBF"第一次写入这段字符不可缺少 $checkBom == 26 $msg = "xEFxBBxBF" . $msg28 $fp = @$filePath,'a'29 @$fp,1)">30 @$fp); ? function checkBOM($filename) $msg = "你好n"; $fileName = 'test'; ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |