PHP读取大文件

今天在博客上看到别人写的一段PHP读取大文件的方法:

/** 
* 返回文件从X行到Y行的内容(支持php5、php4) * @param string $filename 文件名 * @param int $startLine 开始的行数 * @param int $endLine 结束的行数 * @return string
*/ function getFileLines($filename, $startLine = 1, $endLine=50, $method='rb') { $content = array(); $count = $endLine - $startLine; // 判断php版本(因为要用到SplFileObject,PHP>=5.1.0) if(version_compare(PHP_VERSION, '5.1.0', '>=')){ $fp = new SplFileObject($filename, $method); $fp->seek($startLine-1);// 转到第N行, seek方法参数从0开始计数 for($i = 0; $i <= $count; ++$i) { $content[]=$fp->current();// current()获取当前行内容 $fp->next();// 下一行 } }else{//PHP<5.1 $fp = fopen($filename, $method); if(!$fp) return 'error:can not read file'; for ($i=1;$i<$startLine;++$i) {// 跳过前$startLine行 fgets($fp); } for($i;$i<=$endLine;++$i){ $content[]=fgets($fp);// 读取文件行内容 } fclose($fp); } return array_filter($content); // array_filter过滤:false,null,'' }

加上下面 获取文件行数的方法,可以配合使用

/** 
 * 高效率计算文件行数
 */
function count_line($file)
{
  $fp = fopen($file, "rb");
  $i = 0;
  while(!feof($fp)) {        
    if($data = fread($fp, 1024*1024*2)){
      $num = substr_count($data, PHP_EOL);
      $i += $num;
    }
  }
  fclose($fp);
  return $i;
}

 

posted @ 2014-01-16 14:26  WhoAmMe  阅读(3287)  评论(0编辑  收藏  举报