The php fseek function can be used to read large files,
The fseek function is the most common method for php to read large files. It does not need to read all the file content into the memory, but directly operates through pointers, so the efficiency is quite efficient. when using fseek to operate files, there are also a variety of different methods, and the efficiency may be slightly different. Below are two common methods.
Method 1:
First, find the last EOF the file through fseek, then find the starting position of the last row, get the data of this row, find the starting position of the next row, and then take the location of this row, and so on until the $ num row is found. The implementation code is as follows:
It takes 0.0095 seconds to complete the code execution)
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:
The fseek method is used to read the last part of the file, but it is not a one-bit read, but a one-piece read. When each piece of data is read, put the read data in a buf, and then determine whether the last $ num row data has been read by the number of linefeeds (n. the implementation code is as follows:
The execution of the entire Code 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
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!