php批量去除bom头的方法:【<?php ini_set('memory_limit','1024M');function checkdir($basedir) {if ($dh = opendir ( $basedir)(if...】。

本文操作环境:windows10系统、PHP7、thinkpad t480电脑。
我们在实际开发的过程中经常会遇到BOM头,由于这些BOM头的存在经常会导致程序无法正常运行,就像下面这样:

那么我们该如何去解决这种问题呢?其实并不难,我们一起来看下实现代码:
立即学习“PHP免费学习笔记(深入)”;
去除BOM头解决方法:
<?php
ini_set('memory_limit','1024M');
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) { // BOM 的前三个字符的ASCII 码分别为 239 187 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 );
}
$auto=1;
$dir='D:/web/';//项目文件路径
checkDir($dir);
?>推荐学习:php培训
以上就是php如何批量去除bom头的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号