PHPのfseek関数で大きなファイルを操作する方法

方法1:
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));
実行時間:0.0095 (s)

方法2
$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

実行時間:0.0009(s)

方法3:

ini_set('memory_limit’,’-1′);
$file = 'access.log’;
$data = file($file);
$line = $data[count($data)-1];
echo $line;

実行時間:0.0003(s)

Development

Posted by arkgame