PHP reads the X line to Y line contents of a large file
- 2020-06-19 09:52:27
- OfStack
It is necessary to read a few lines of a file, but the file is relatively large, so I studied the method of php to read a few lines of a large file and wrote a method, the code is as follows (with comments) :
If a cache file can be kept at 1 row, then reading the specified number of rows with the algorithm will be much faster than picking them all out.
In tests, this line of code reached the last line of 8MB text, with a memory footprint of 49KB, which was not bad, but 29KB with fgets skipping, which was still better.
Good results, SplFileObject class function is better.
If a cache file can be kept at 1 row, then reading the specified number of rows with the algorithm will be much faster than picking them all out.
$fp->seek($startLine - 1);
In tests, this line of code reached the last line of 8MB text, with a memory footprint of 49KB, which was not bad, but 29KB with fgets skipping, which was still better.
function getFileLines($filename, $startLine = 1, $endLine = 50, $method = 'rb'){
$content = array();
if (version_compare(PHP_VERSION, '5.1.0', '>=')) { // judge php Version (because it will be used SplFileObject . PHP>=5.1.0 )
$count = $endLine - $startLine;
$fp = new SplFileObject($filename, $method);
$fp->seek($startLine - 1); // Turn to the first N line , seek Method parameters from 0 Start counting
for ($i = 0; $i <= $count; ++$i) {
$content[] = $fp->current(); // current() Gets the current line content
$fp->next(); // Under the 1 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 former $startLine line
fgets($fp);
}
for ($i; $i <= $endLine; ++$i) {
$content[] = fgets($fp); // Read the contents of the file line
}
fclose($fp);
}
return array_filter($content); // array_filter Filtering: false,null,''
}
Good results, SplFileObject class function is better.