PHP implementation code for reading the contents of lines X to Y of a large file_PHP tutorial

WBOY
Release: 2016-07-21 15:03:00
Original
866 people have browsed it

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.

www.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...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template