用PHP解决万恶的BOM

<?php
$path = dirname(__FILE__);

scandDir($path);


function bomtoutf8($filename)
{
	$ef = 239;
	$bb = 187;
	$bf = 191;

	if (is_dir($filename)) return;
	$fd = fopen($filename, "rb");
	if (!$fd) exit($filename);
	$headers = fread($fd, 3);
	fclose($fd);
	
	if (strlen($headers) < 3) return;

	if (ord($headers[0]) == $ef && 
		ord($headers[1]) == $bb &&
		ord($headers[2]) == $bf
		) {
		echo $filename, "\n";
		$content = file_get_contents($filename);
		if (!$content) {
			exit("file get contents failed");
		}
		$len = strlen($content);
		$content = substr($content, 3);

		if ($content === false && $len!=3) {
			exit("sbustr failed");
		} else if ($content === false && $len==3){
			$content = "";
		}
		$ret = file_put_contents($filename, $content, LOCK_EX);
		if ($ret === false) {
			exit("file put contents failed");
		}
		echo "successed file ", $filename, "\n";
	}


}

function scandDir($path)
{
	$d = dir($path);
	if (!$d) exit("dir failed");

	while (false !== ($entry = $d->read())) {
		if ($entry == '.' || $entry == '..') {
			continue;
		}
		$filename = $path . DIRECTORY_SEPARATOR . $entry;
	//	echo $filename, "\n";
		if (is_dir($filename)) {
			scandDir($filename);
		} else {
			bomtoutf8($filename);
		}
	}
}


友情提示:代码是批量处理目录下(包括子目录)的所有带BOM文件,使用前需备份

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值