It is very easy to read files in PHP, but how to fix them if the files you read are very large? We can directly use Fseek to do large file operation, this article introduces you to PHP using the Fseek function to read large files, the need for friends can refer to
PHP reads 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 many different ways to use fseek to manipulate files, and the efficiency may also be slightly differentiated, The following are two common methods.
Method One:
First, find the last EOF of the file by fseek, then find the beginning of the last line, take this row of data, then find the starting position of the next line, then take the position of this line, and so on, until the $num line is found. The implementation code is as follows:
Complete code Execution time 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 use fseek way from the end of the file to read, but this is not a one read, but a piece of reading, each read a piece of data, the data will be read in a buf, and then by the number of newline characters (n) to determine whether the last $num rows of data. Implementation code is as follows
The entire code execution takes time 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