Need to read a few lines of a file, but the file is relatively large, so I studied the next PHP read a few lines of the contents of the method, wrote a method, the code is as follows (added note):
If the cached file can be saved on a single line, and the algorithm reads the specified number of rows, it will naturally be much faster than the entire read out selection. But PHP seems to be weak in this area, not very good operation. Even if the use of splfileobject is still not particularly desirable, memory pressure exists.
Copy Code code as follows:
$FP->seek ($startLine-1);
After testing, this line of code in 8MB text to go to the last row, memory footprint of 49KB, is not bad. Instead of using the fgets skipped mode with the Fopen method, it costs 29KB of RAM, fopen still prevails.
Copy Code code as follows:
function Getfilelines ($filename, $startLine = 1, $endLine =, $method = ' rb ') {
$content = Array ();
if (Version_compare (php_version, ' 5.1.0 ', ' >= ')) {//Judge PHP version (because you want to use splfileobject,php>=5.1.0)
$count = $endLine-$startLine;
$fp = new Splfileobject ($filename, $method);
$FP->seek ($startLine-1); Go to Nth row, the Seek method parameter counts starting at 0
for ($i = 0; $i <= $count; + + $i) {
$content [] = $fp->current (); Current () Gets the contents of the line
$FP->next (); Next line
}
else {//php<5.1
$fp = fopen ($filename, $method);
if (! $fp)
Return ' Error:can not read file ';
for ($i = 1; $i < $startLine + + $i) {//Skip front $startline Line
Fgets ($FP);
}
for ($i; $i <= $endLine; + + $i) {
$content [] = Fgets ($FP); Read File line contents
}
Fclose ($FP);
}
Return Array_filter ($content); Array_filter filter: False,null, "
}
The effect is good, splfileobject class function is better.