需要读取一个文件的几行内容,但是文件比较大,所以研究了下php读取大文件的几行内容的方法,写了一个方法,代码如下
需要读取一个文件的几行内容,但是文件比较大,虚拟主机,所以研究了下php读取大文件的几行内容的方法,服务器空间,写了一个方法,代码如下(加了注释):
缓存文件如果能够保存在一行, 而利用算法读取指定的行数, 自然会比全部读出来挑选要快得多. 但php似乎这方面比较弱, 不太好操作. 就算使用SplFileObject仍然不是特别可取, 内存压力存在.
复制代码 代码如下:
$fp->seek($startLine - 1);
经过测试, 此行代码在8MB文本中游走到最后一行, 内存占用为49KB, 还算不错. 换成fopen方式用fgets跳过的模式, 则花费29KB的内存, fopen还是占优势.
复制代码 代码如下:
function getFileLines($filename, $startLine = 1, $endLine = 50, $method = 'rb'){
$content = array();
if (version_compare(PHP_VERSION, '5.1.0', '>=')) { // 判断php版本(因为要用到SplFileObject,网站空间,PHP>=5.1.0)
$count = $endLine - $startLine;
$fp = new SplFileObject($filename, $method);
$fp->seek($startLine - 1); // 转到第N行, seek方法参数从0开始计数
for ($i = 0; $i $content[] = $fp->current(); // current()获取当前行内容
$fp->next(); // 下一行
}
} else { //PHP$fp = fopen($filename, $method);
if (!$fp)
return 'error:can not read file';
for ($i = 1; $i fgets($fp);
}
for ($i; $i $content[] = fgets($fp); // 读取文件行内容
}
fclose($fp);
}
return array_filter($content); // array_filter过滤:false,null,''
}
效果不错, SplFileObject类功能比较好.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use