PHP批量移除UTF-8文件BOM头的代码实例

PHP程序猿应该都知道,对于PHP来说,BOM是一个大麻烦,所以最近就写了一个可以批量移除一个目录下UTF-8文件BOM头的PHP文件,下面分享给大家:)

如果不知道BOM是什么,可以参阅这里:http://baike.baidu.com/subview/126558/5073180.htm#viewPageContent


<?php
/** 
 * ljfrocky@gmail.com  RockyLiang
 * 遍历一个目录及其子目录,并去除所有文件头部的BOM
 */
set_time_limit(0);

// 发现BOM时是否自动清除
$auto = true;
// 要遍历的目录,支持相对路径和绝对路径
$base_dir = '.';

recurse_remove_bom($base_dir);

function recurse_remove_bom($path = '.') {
	$real_path = realpath($path);
	if ($real_path === false) {
		echo "[$path] is not exist";
		return;
	}

	if (!is_dir($real_path)) {
		echo "[$real_path] is not a directory";
		return;
	}

	$dh = @opendir($real_path);
	if ($dh === false) {
		echo "Open [$real_path] failed";
		return;
	}

	while (($file = readdir($dh)) !== false) {
		if ($file == '.' || $file == '..') {
			continue;
		}

		$sub_dir = $real_path . DIRECTORY_SEPARATOR . $file;
		if (is_dir($sub_dir)) {
			recurse_remove_bom($sub_dir);
		} else {
			echo "File : [$sub_dir] " . check_bom($sub_dir) . "<br/>";
		}
	}

	closedir($dh);
}

function check_bom($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) {
			$rest = substr($contents, 3);
			$ret = file_put_contents($filename, $rest, LOCK_EX);
			$str = ($ret === false)
				? '<font color="red">BOM found, automatically removed failed.</font>'
				: '<font color="red">BOM found, automatically removed success.</font>';
			return $str;
		} else {
			return '<font color="red">BOM found.</font>';
		}
	} else {
		return '<font color="green">BOM Not Found.</font>';
	}
}
?>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值