PHP read large files, using the Fseek function is the most common way, it does not need to read all the contents of the file into memory, but directly through the pointer to operate, so the efficiency is quite efficient. There are several different ways to manipulate a file using fseek, and there may be a slight difference in efficiency, Here are two common methods.
Method One:
First through the fseek find the last EOF of the file, then find the starting position of the last line, take this row of data, find the first line of the starting position, and then take the position of the line, and so on until the $num line is found. The implementation code is as follows:
Complete code Execution time consuming 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 Two:
Or in a fseek way from the end of the file to read, but at this time is not a one read, but a piece of reading, each read a piece of data, the read data in a buf, and then through the number of line breaks (n) to determine whether the last $num row of data has been read. Implementation code is as follows
Complete code Execution time consuming 0.0009 (s).
$fp = fopen ($file, "R");
$line = ten;
$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 to help you, thank you for your support for this site!