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;
}
相关文档:
岗位职责
1、协助系统架构设计师进行系统架构设计工作;
2、承担Web应用核心模块的设计/实现工作;
3、承担主要开发工作,对代码质量及进度负责;
4、进行关键技术验证以及技术选型工作;
5、和产品经理沟通并确定产品开发需求;
岗位要求
1、具有互联网领域相关项目开发工作经验,对互联网业务以及技术有相 ......
原帖地址:http://www.phpma.com/english/20071215/640.html
Description
array explode
( string separator, string string [, int limit])phpma.com
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string separator
. If limit
is ......
/*
用PHP的DOM控件来创建XML输出
设置输出内容的类型为xml
*/
header('Content-Type: text/xml;');
//创建新的xml文件
$dom = new DOMDocument('1.0', 'utf-8');
//建立<response>元素
$response = $dom->createElement('response');
$dom->appendChild($response);
//建立<books>元素并将其作 ......