PHP实现类似tail命令读取最后n行的方法
原文出自: http://www.hly1980.cn/archives/118.html
需要分析日志时tail命令可是常需要用到的,可惜php内并没有提供类似的方法,所以自己实现了一个。
调用方式为tail($filename, $rows),每次默认读取1024字节作为缓冲,返回字符串数组,文件尾的行靠前(这里的行为和tail有所区别,如果需要以原序返回的请自行调用array_reverse)。
代码如下:
/**
* 读取文件最后若干行的数据
*
* @param string $filename
* 文件名
* @param string $rows
* 行数
* @param string $size
* 内存缓冲区大小,默认为1024字节
* @param string $ending
* 行尾分隔符,默认为\n
* @return array
* 读取成功则返回字符串数组,文件尾的字符串靠前,读取失败则返回false
*/
function tail($filename, $rows, $size = 1024, $ending = "\n") {
$ret = false;
if ($rows > 0 && $fp = fopen($filename, 'rb')) {
$pos = filesize($filename);
$ret = array();
flock($fp, LOCK_SH);
$data = '';
$found = 0;
while ($found < $rows) {
$pos = $pos - $size;
if ($pos < 0) {
$size = 1024 + $pos;
$pos = 0;
}
fseek($fp, $pos, SEEK_SET);
$data = fread($fp, $size) . $data;
$tmp = explode($ending, $data);
$count = count($tmp);
for ($i = 1; $i < $count; $i++) {
$ret[] = $tmp[$count - $i];
$found++;
if ($found >= $rows) {
break;
}
}
$data = $tmp[0];
if ($pos <= 0) {
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
}
return $ret;
}
相关文档:
用php生成excel文件
<?
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=test.xls");
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
e ......
getenv() 取得系统的环境变量(预定义变量)
$spager=getenv('SERVER_NAME');
“PHP_SELF”
当前正在执行脚本的文件名,与 document root 相关。举例来说,在 URL 地址为 [url]http://example.com/test.php/foo.bar[/url] 的脚本中使用 $_SERVER['PHP_SELF'] 将会得到 /test.php/foo.bar 这个结 ......
这两天在捣鼓PHP,去ecshop和phpwind下载了一个商城和一个论坛。两个都需要安装mysql的服务器,于是我按照教程进行安装。结果发现每次都是到连接数据库的地方就变成空白页了。死活找不出来问题。后来在余建的指导下,发现原来是PHP的版本过高。真是郁闷。
现在我把我最近配置的过程写出来。
所需软件:
apache_2.2.14-wi ......
PHP中的MYSQL常用函数总结
1、mysql_connect()-建立数据库连接
格式:
resource mysql_connect([string hostname [:port] [:/path/to/socket] [, string username] [, string password]])
例:
$conn = @mysql_connect("localhost", "username", "password") or dir( ......