Home  >  Article  >  Backend Development  >  Detailed examples of two methods for reading large files using the php fseek function

Detailed examples of two methods for reading large files using the php fseek function

怪我咯
怪我咯Original
2017-07-09 10:21:371290browse

Reading files in php is very simple, but if the file read is very large, how to solve it? We can directly use fseek to perform large file operations. This article introduces php to use fseekfunction to read large files. Friends in need can refer to

php to read large files, use The fseek function is the most common method. It does not need to read all the contents of the file into memory, but operates directly through pointers, so the efficiency is quite efficient. There are also many different methods when using fseek to operate files. Methods and efficiency may be slightly different. The following are two commonly used methods.

Method 1:

First find the last EOF of the file through fseek. Then find the starting position of the last row, take the data of this row, then find the starting position of the next row, then take the position of this row, and so on, until the $num row is found. The implementation code is as follows:

The entire code execution takes 0.0095 (s)

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));

Method 2:

Still use fseek to start from the end of the file Start reading, but this time it is not reading bit by bit, but reading piece by piece. Every time a piece of data is read, the read data is placed in a buf, and then the number of newline characters (n) is passed. To determine whether the last $num rows of data have been read. The implementation code is as follows

The entire code execution takes 0.0009(s).

$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

The above is the detailed content of Detailed examples of two methods for reading large files using the php fseek function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn