Heim  >  Artikel  >  Backend-Entwicklung  >  PHP读取大文件的类SplFileObject用法详解

PHP读取大文件的类SplFileObject用法详解

WBOY
WBOYOriginal
2016-07-25 08:53:362208Durchsuche
  1. /** 返回文件从X行到Y行的内容(支持php5、php4)
  2. * @param string $filename 文件名
  3. * @param int $startLine 开始的行数
  4. * @param int $endLine 结束的行数
  5. * @return string
  6. */
  7. function getFileLines($filename, $startLine = 1, $endLine=50, $method='rb') {
  8. $content = array();
  9. $count = $endLine - $startLine;
  10. // 判断php版本(因为要用到SplFileObject,PHP>=5.1.0)
  11. if(version_compare(PHP_VERSION, '5.1.0', '>=')){
  12. $fp = new SplFileObject($filename, $method);
  13. $fp->seek($startLine-1);// 转到第N行, seek方法参数从0开始计数
  14. for($i = 0; $i $content[]=$fp->current();// current()获取当前行内容
  15. $fp->next();// 下一行
  16. }
  17. }else{//PHP $fp = fopen($filename, $method);
  18. if(!$fp) return 'error:can not read file';
  19. for ($i=1;$i fgets($fp);
  20. }
  21. for($i;$i $content[]=fgets($fp);// 读取文件行内容
  22. }
  23. fclose($fp);
  24. }
  25. return array_filter($content); // array_filter过滤:false,null,''
  26. }
复制代码

说明: 上面都没加”读取到末尾的判断”:!$fp->eof() 或者 !feof($fp),加上这个判断影响效率,自己加上测试很多很多很多行的运行时间就晓得了,而且这里加上也完全没必要。 从上面的函数就可以看出来使用SplFileObject比下面的fgets要快多了,特别是文件行数非常多、并且要取后面的内容的时候。 fgets要两个循环才可以,并且要循环$endLine次。 此方法花了不少功夫,测试了很多中写法,就是想得出效率最高的方法。哪位觉得有值得改进的欢迎赐教。 使用,返回35270行-35280行的内容: 代码:

  1. echo '
    ';
  2. var_dump(getFileLines('test.php',35270,35280));
  3. echo '';
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php汉字转码的例子 Nächster Artikel:PHP删除数组中空值