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