I need to read several lines of content from a file, but the file is large. So I studied how php can read several lines of content from a large file and wrote a method. The Code is as follows:
I need to read several lines of content from a file, but the file is large. So I studied how php can read several lines of content from a large file and wrote a method. The Code is as follows:
I need to read several lines of content from a file, but the file is large and the virtual host. So I studied how php can read several lines of content from a large file. I wrote a method for server space, the Code is as follows (with comments added ):
If the cached file can be saved in one row, and the algorithm is used to read the specified number of rows, it is naturally much faster to select than to read all. however, php seems to be relatively weak in this aspect and is not very easy to operate. even if SplFileObject is used, memory pressure exists.
The Code is as follows:
$ Fp-> seek ($ startLine-1 );
After testing, this line of code reaches the last line in the 8 Mb text, and the memory usage is 49KB, which is not bad. if you use the fgets skip mode in the fopen mode, it will consume 29KB of memory. The fopen mode is dominant.
The Code is as follows:
Function getFileLines ($ filename, $ startLine = 1, $ endLine = 50, $ method = 'rb '){
$ Content = array ();
If (version_compare (PHP_VERSION, '5. 1.0 ','> = ') {// determine the php version (because SplFileObject, website space, PHP> = 5.1.0 is used)
$ Count = $ endLine-$ startLine;
$ Fp = new SplFileObject ($ filename, $ method );
$ Fp-> seek ($ startLine-1); // go to row N, and the seek method parameter starts counting from 0.
For ($ I = 0; $ I <= $ count; ++ $ I ){
$ Content [] = $ fp-> current (); // current () Get the content of the current row
$ Fp-> next (); // next row
}
} Else {// PHP <5.1
$ Fp = fopen ($ filename, $ method );
If (! $ Fp)
Return 'error: can not read file ';
For ($ I = 1; $ I <$ startLine; ++ $ I) {// skip the previous $ startLine line
Fgets ($ fp );
}
For ($ I; $ I <= $ endLine; ++ $ I ){
$ Content [] = fgets ($ fp); // read the content of the file row
}
Fclose ($ fp );
}
Return array_filter ($ content); // array_filter: false, null ,''
}
The results are good, and the SplFileObject class features better.