<?php

$start = microtime(TRUE);
$filesize = filesize('SHUIPING_YANG.log');
$fp = fopen('SHUIPING_YANG.log', 'r');
$getfp = fopen('SHUIPING_YANG.log', 'r');

$lines = 0;
$line = 0;

//获取文件的一行内容,注意:需要php5才支持该函数;
//第一种方法,可以设置定界符"\r \t \n",注意设置定界符的时候要用双引号!
while (stream_get_line($fp, $filesize,"\n")) {
$line++;
}
fclose($fp); //关闭文件

while (fgets($getfp)) {
$lines++;
}
fclose($getfp); //关闭文件

printf("stream_get_line函数所取得的文件行数为:%s", $line);
echo '<br>';
printf("fgets函数所取得的文件行数为:%s", $lines) ;

echo '<br>';
$end = microtime(TRUE);
echo '耗时' . $deltime = $end - $start;


//第二种方法
/*获取大文件最后N行方法
原理:
首先通过fseek找到文件的最后一位EOF,然后找最后一行的起始位置,取这一行的数据,再找次一行的起始位置, 再取这一行的位置,依次类推,直到找到了$num行。
*/

$file = "F:\access_log";
var_dump(tail($file, 10));

function tail($file, $num) {
$fp = fopen($file, "r");
$pos = -2;
$eof = "";
$head = false; //当总行数小于Num时,判断是否到第一行了
$lines = array();
while ($num > 0) {
while ($eof != "\n") {
if (fseek($fp, $pos, SEEK_END) == 0) {
//fseek成功返回0,失败返回-1
$eof = fgetc($fp);
$pos--;
} else {
//当到达第一行,行首时,设置$pos失败
fseek($fp, 0, SEEK_SET);
$head = true; //到达文件头部,开关打开
break;
}
}
array_unshift($lines, fgets($fp));
if ($head) {break;} //这一句,只能放上一句后,因为到文件头后,把第一行读取出来再跳出整个循环
$eof = "";
$num--;
}
fclose($fp);
return $lines;
}
?>

以上例子输出结果为:
stream_get_line函数所取得的文件行数为:272717
fgets函数所取得的文件行数为:272717
耗时0.727095

看到了吧?速度还是蛮快的,两种方法加起来耗时还不到一秒,文件一共有27万多行!!!!

读取大文件内容:

function getbigfile() {
$file_path = "D:/wamp/www/test/input.txt";
$handle = fopen($file_path, "r+");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 8000);
echo $buffer;
}
fclose($handle);
}
}

//getbigfile();
//die;

//返回文件从X行到Y行的内容
function getFileLine($file_path,$starline=1,$endline=5,$open_mode = "rb+"){
$fp = new SplFileObject($file_path, $open_mode);
$fp->seek($starline - 1); // 转到第N行, seek方法参数从0开始计数
for($i=0;$i<=$endline;$i++){
$content[] = $fp->current(); //current()获取当前行内容
$fp->next(); // 下一行
}
return $content;
}
$file_path = "D:/wamp/www/test/input.txt";