Need to read a few lines of a file, but the file is relatively large, so the next PHP read a few lines of the content of the method, wrote a method, the code is as follows (annotated):
If the cache 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 respect, not very good operation. Even if using splfileobject is still not particularly desirable, memory pressure exists.
Copy CodeThe code is as follows:
$FP->seek ($startLine-1);
After testing, this line of code in the 8MB text reaches the last line, memory consumption of 49KB, is good. Switch to fopen mode with fgets skip pattern, then spend 29KB of memory, fopen or dominant.
Copy CodeThe code is as follows:
function Getfilelines ($filename, $startLine = 1, $endLine =, $method = ' rb ') {
$content = Array ();
if (Version_compare (php_version, ' 5.1.0 ', ' >= ')) {//Judge PHP version (because splfileobject,php>=5.1.0 is used)
$count = $endLine-$startLine;
$fp = new Splfileobject ($filename, $method);
$FP->seek ($startLine-1); Go to Nth row, the Seek method parameter counts from 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 previous $startline lines
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, "
}
Good effect, Splfileobject class function is better.
http://www.bkjia.com/PHPjc/327872.html www.bkjia.com true http://www.bkjia.com/PHPjc/327872.html techarticle need to read a file a few lines of content, but the file is relatively large, so the next PHP read a few lines of the content of the method, wrote a method, the code is as follows (annotated): Slow ...