I need to read a few lines of a file, but the file is relatively large, so I studied the method of reading several lines of a large file in PHP and wrote a method. The code is as follows (with comments):
Cache file if Being able to save in one line, and using the algorithm to read the specified number of lines will naturally be much faster than reading out and selecting them all. However, PHP seems to be weak in this regard and not easy to operate. Even using SplFileObject is still not particularly advisable due to memory pressure. Exists.
Copy code The code is as follows:
$fp->seek($startLine - 1);
After testing, this line of code travels to the last line in the 8MB text, and the memory usage is 49KB, which is not bad. Switching to fopen mode and using fgets skip mode, it will cost With 29KB of memory, fopen still has the advantage.
Copy code 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 is used, PHP>=5.1.0)
$count = $endLine - $startLine;
$fp = new SplFileObject($filename, $method) ;
$fp->seek($startLine - 1); // Go to line N, the seek method parameters start counting from 0
for ($i = 0; $i <= $count; ++$i) {
$content[] = $fp->current(); // current() gets the current line content
$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 the previous $startLine line
fgets($fp);
}
for ($i; $i <= $endLine; ++$i) {
$content[] = fgets($fp); // Read file line content
}
fclose($ fp);
}
return array_filter($content); // array_filter filtering: false,null,''
}
The effect is good, SplFileObject class function Better.
http://www.bkjia.com/PHPjc/327872.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327872.htmlTechArticleNeed to read several lines of a file, but the file is relatively large, so I studied php to read large files I wrote a method based on a few lines of content. The code is as follows (with comments): Slow...