小站在一次使用接口传输的过程遇到bom文件,使得接收过来的数据无法使用,在网上找到php版的去除bom文件,但是没有检测子文件夹功能和排除不需要检测的文件夹,于是在此基础上用面向对象的方式做了些修改。
<?php
/**
* 此文件用于快速测试UTF8编码的文件是不是加了BOM,并可自动移除
* 增加了检测子文件夹和排除不要检测的文件夹
*
* @author yangzy
*/
$bom = new bom();
$bom->run();
class bom
{
public $basedir = "./../trunk_bugfix";//修改此行为需要检测的目录,点表示当前目录
public $auto = '1';//是否自动移除发现的BOM信息。1为是,0为否。
public $file_arr = array('.svn');//不需要检测文件夹
public function __construct()
{
}
/**
* 运行程序
*/
public function run($basedir = '')
{
$basedir || $basedir = $this->basedir;
if ($dh = opendir($basedir)) {
while (($file = readdir($dh)) !== false) {
if ($file!='.' && $file!='..' && !is_dir($basedir."/".$file))
{
echo $basedir."/".$file.':'.$this->checkBOM($basedir."/$file")." <br>";
}
elseif ($file!='.' && !in_array($file, $this->file_arr) && $file!='..' && is_dir($basedir."/".$file))
{
$this->run($basedir."/".$file);
}
}
closedir($dh);
}
}
/**
* 检测bom文件
*/
public function checkBOM($filename)
{
$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 ($this->auto == 1) {
$rest=substr($contents, 3);
$this->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.");
}
/**
* 重新生成文件
*/
public function rewrite($filename, $data)
{
$filenum=fopen($filename,"w");
flock($filenum,LOCK_EX);
fwrite($filenum,$data);
fclose($filenum);
}
}
转自: http://www.ibihuo.com/show-59.html