Skip to content

Instantly share code, notes, and snippets.

@Jason-cqtan
Created March 14, 2019 07:00
Show Gist options
  • Save Jason-cqtan/6fa18742df3859c25f88436fe1065434 to your computer and use it in GitHub Desktop.
Save Jason-cqtan/6fa18742df3859c25f88436fe1065434 to your computer and use it in GitHub Desktop.
读取大文件局部内容
<?php
//方法一、使用linux命令
file = 'access.log';
$file = escapeshellarg($file); // 对命令行参数进行安全转义
$line = `tail -n 1 $file`;
echo $line;
//方法二、使用php的fseek
//第一种:首先通过fseek找到文件的最后一位EOF,然后找最后一行的起始位置,取这一行的数据,再找次一行的起始位置,再取这一行的位置,依次类推,直到找到了$num行。
function tail($fp,$n,$base=5)
{
assert($n>0);
$pos = $n+1;
$lines = array();
while(count($lines)< =$n){
try{
fseek($fp,-$pos,SEEK_END);
} catch (Exception $e){
fseek(0);
break;
}
$pos *= $base;
while(!feof($fp)){
array_unshift($lines,fgets($fp));
}
}
return array_slice($lines,0,$n);
}
var_dump(tail(fopen("access.log","r+"),10));
//第二种:还是采用fseek的方式从文件最后开始读,但这时不是一位一位的读,而是一块一块的读,每读一块数据时,就将读取后的数据放在一个buf里,然后通过换行符(\n)的个数来判断是否已经读完最后$num行数据.
$fp = fopen($file, "r");
$line = 10;
$pos = -2;
$t = " ";
$data = "";
while ($line > 0) {
while ($t != "\n") {
fseek($fp, $pos, SEEK_END);
$t = fgetc($fp);
$pos --;
}
$t = " ";
$data .= fgets($fp);
$line --;
}
fclose ($fp);
echo $data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment