-
- /**Returns the content of the file from line return string
- */
- function getFileLines($filename, $startLine = 1, $endLine=50, $method='rb') {
- $content = array() ;
- $count = $endLine - $startLine;
- // Determine the php version (because SplFileObject is used, PHP>=5.1.0)
- if(version_compare(PHP_VERSION, '5.1.0', '>=') ){
- $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 row 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 filter: false,null,' '
- }
-
- Copy code
Instructions:
The above does not include the "judgment of reading to the end": !$fp->eof() or !feof($fp). In addition, this judgment affects efficiency. You will know by testing the running time of many, many, many lines. , and it is completely unnecessary to add it here.
From the above function, we can see that using SplFileObject is much faster than fgets below, especially when the number of file lines is very large and the following content needs to be fetched.
fgets requires two loops, and it needs to loop $endLine times.
This method took a lot of effort and tested many Chinese writing methods, just to find the most efficient method. If anyone thinks there is anything worth improving, please let me know.
Use, return the content of lines 35270-35280:
Code:
echo ' ';<ol>var_dump(getFileLines('test.php',35270,35280));<li>echo ' ';
Copy Code
|