Home > php教程 > php手册 > body text

php 使用file_get_contents读取大文件的方法

WBOY
Release: 2016-06-06 20:17:36
Original
1228 people have browsed it

本文介绍了在php中使用file_get_contents函数读取大文件的方法,并附上了示例以及使用小技巧,非常的实用,这里推荐给大家

当我们遇到文本文件体积很大时,比如超过几十M甚至几百M几G的大文件,用记事本或者其它编辑器打开往往不能成功,因为他们都需要把文件内容全部放到内存里面,这时就会发生内存溢出而打开错误,遇到这种情况我们可以使用PHP的文件读取函数file_get_contents()进行分段读取。

函数说明
string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。

file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

应用:

复制代码 代码如下:


$str = $content=file_get_contents("2.sql",FALSE,NULL,1024*1024,1024);
echo $str;

如果针对较小文件只是希望分段读取并以此读完可以使用fread()函数

复制代码 代码如下:


$fp=fopen('2.sql','r');
while (!feof($fp)){
$str.=fread($fp, filesize ($filename)/10);//每次读出文件10分之1
//进行处理
}

echo $str;

以上就是如何使用file_get_contents函数读取大文件的方法,超级简单吧,,需要的小伙伴直接搬走!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!