1, facing the problem analysis
Read ordinary small files we generally use fopen or file_get_contents is very convenient and simple, the former can be recycled, the latter can be read one time, but all the contents of the file loaded to operate once. If the load of the file is particularly large, such as hundreds of M, G, when the performance is very poor, then there is no big file in PHP processing functions or classes it? The answer is: yes.
2, Splfileobject class efficiently solve large file reading problems
Starting with PHP 5.1.0, the SPL library adds two standard file operation classes for Splfileobject and Splfileinfo.
In the literal sense, it can be seen that splfileobject is more powerful than splfileinfo.
Yes, Splfileinfo is only used to get some property information about a file, such as file size, file access time, file modification time, suffix name equivalence, and Splfileobject is a file operation class that inherits Splfileinfo these features and adds many file handling class action methods.
/** Returns the contents of the file from line x to line Y (supports PHP5, PHP4)
* @param string $filename file name
* @param int $startLine The number of lines to start
* @param int $endLi NE end Lines
* @return string
*/
Function getfilelines ($filename, $startLine = 1, $endLine =50, $method = ' rb ') {
$ Content = Array ();
$count = $endLine-$startLine;
//Determine the PHP version (because you want to use splfileobject,php>=5.1.0)
if (Version_compare (php_version, ' 5.1.0 ', ' >= ')) {
$fp = New Splfileobject ($filename, $method);
$fp->seek ($startLine-1);//go to Nth row, the Seek method argument starts with 0 count
for ($i = 0; $i <= $count; + + $i) {
$content []= $fp Current ();//Present () Gets the contents
$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, '
}
Ps:
(1), the above did not add "read to the end of the judgment":! $fp->eof () or!feof ($FP), the results of practice plus this judgment affect efficiency, and there is absolutely no need to add.
(2), from the above functions and practices can be seen to use the Splfileobject analogy below the fgets function efficiency is much higher, especially the number of file rows, and to take the more back content. Fgets need two loops to be able.