Home  >  Article  >  Backend Development  >  Detailed explanation of usage of class SplFileObject for reading large files in PHP

Detailed explanation of usage of class SplFileObject for reading large files in PHP

WBOY
WBOYOriginal
2016-07-25 08:53:362250browse
  1. /**Returns the content of the file from line return string
  2. */
  3. function getFileLines($filename, $startLine = 1, $endLine=50, $method='rb') {
  4. $content = array() ;
  5. $count = $endLine - $startLine;
  6. // Determine the php version (because SplFileObject is used, PHP>=5.1.0)
  7. if(version_compare(PHP_VERSION, '5.1.0', '>=') ){
  8. $fp = new SplFileObject($filename, $method);
  9. $fp->seek($startLine-1);//Go to line N, the seek method parameters start counting from 0
  10. for($i = 0; $i <= $count; ++$i) {
  11. $content[]=$fp->current();// current() gets the current row content
  12. $fp->next() ;//Next line
  13. }
  14. }else{//PHP<5.1
  15. $fp = fopen($filename, $method);
  16. if(!$fp) return 'error:can not read file';
  17. for ($ i=1;$i<$startLine;++$i) {// Skip the previous $startLine line
  18. fgets($fp);
  19. }
  20. for($i;$i<=$endLine;++$i ){
  21. $content[]=fgets($fp);//Read file line content
  22. }
  23. fclose($fp);
  24. }
  25. return array_filter($content); // array_filter filter: false,null,' '
  26. }
  27. 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
  • Statement:
    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