版权声明:本文为博主原创文章,转载文章请联系博主 [email protected] https://blog.csdn.net/qq_35070711/article/details/78015446
BOM认知
BOM(Byte Order Mark),字节顺序标记,,出现在文本文件头部,Unicode编码标准中用于标识文件是采用哪种格式的编码。编码是\xEF\xBB\xBF,BOM头是UTF-8来告诉编辑器:这是UTF8编码。
PHP和BOM
PHP在设计之初并没有考虑到BOM头的问题,所以在编解码的时候很容易出现问题,比如以下问题,json_decode,当解码的string有BOM头的时候json_decode就解析失败,返回NULL。然而这并不是我们想要的结果。
去除BOM的办法
1、直接嵌入到代码中:
//关于\xEF\xBB\xBF,看第一点BOM认知
$result = trim($result, "\xEF\xBB\xBF");
print_r(json_decode($result, true));
exit;
2、写一个去除BOM的PHP文件:
此方法优点:简单,出现BOM,调用一次文件就OK了
将以下代码写到一个php文件中,如:bom.php 放置在你的项目中
调用一次就可以去除项目文件中的BOM,代码如下:
//remove the utf-8 boms
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[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);
}
?>