Two ways to read large files using php fseek function

高洛峰
Release: 2023-03-03 17:18:01
Original
1654 people have browsed it

The most common way for PHP to read large files is to use the fseek function. 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. When using fseek to perform operations on the file There are many different methods during operation, and the efficiency may be slightly different. The following are two commonly used methods.

Method 1:

First find the last EOF of the file through fseek, and then find the beginning of the last line. The starting position, get 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));
Copy after login

Method 2:

Still use fseek to read from the end of the file, but this time it is not reading one by one, but one by one Reading, 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 used to determine whether the last $num rows of data have been read. The implementation code is as follows

The entire It takes 0.0009(s) to complete the code execution.

$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
Copy after login

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more related articles on the two methods of reading large files using the php fseek function, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template