I recently wrote a small program that needs 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, I wrote a method and the code is as follows (with comments added)
I recently wrote a small program that needs 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, I wrote a method and the code is as follows (with comments added ):
// Return the content of the object from row X to Row Y (php5 and php4 are supported)
Function getFileLines ($ filename, $ startLine = 1, $ endLine = 50, $ method = 'RB '){
$ Content = array ();
$ Count = $ endLine-$ startLine;
If (version_compare (PHP_VERSION, '5. 1.0 ','> = ') {// Determine the php version (because SplFileObject, PHP> = 5.1.0)
$ Fp = new SplFileObject ($ filename, $ method );
$ Fp-> seek ($ startLine-1); // go to row N, 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 ,''
}
Ps:
No "read to the end judgment" is added above ":! $ Fp-> eof () or! Feof ($ fp), coupled with this judgment, affects the efficiency. you can test the running time of many and many rows by yourself, and it is completely unnecessary to add it here.
From the above function, we can see that the use of SplFileObject is much faster than the fgets below, especially when the number of file lines is large and the subsequent content is to be retrieved. Fgets requires two loops and $ endLine loops.
This method took a lot of effort to test a lot of writing, that is, to find the most efficient method. Anyone who thinks it is worthy of improvement should give us some advice.
If yes, the following content is returned:
Echo'
';var_dump(getFileLines('test.php',35270,35280))