2011年4月21日

[PHP]讀取檔案的最後幾行

$n = 20 //要讀的行數
$fileName = "name"; //要讀的檔案
$fp = fopen( $fileName, 'r' ); // 開啟檔案
fseek($fp,0,SEEK_END);
$c = ftell($fp);
$countline = 0;
while ($c > 0 && $countline < $n ) { //從最後往前找第$n個\n
  if ( fgetc( $fp ) == chr(10) ) $countline += 1;
  $c -= 1;
  fseek($fp,$c) ;
}
$data_array=explode(chr(10),fread($fp, filesize($fileName)));
fclose($fp);

$data_array 為讀取結果

0 意見:

張貼意見