Home > Backend Development > PHP Tutorial > php读取大文件的1点疑问

php读取大文件的1点疑问

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 11:22:00
Original
1071 people have browsed it

php读取大文件的一点疑问
我要分析一个6G的log文件,比对每行文件是否符合我的要求,程序如下

<br />$file_path = 'd:\work\workplace\test\file\system.log';<br />$file = fopen($file_path, 'r');<br />$key = md5(0);<br />$i = 1;<br />while (!feof($file)) {<br />    $buff = fgets($file);<br />    if ($buff == $key . "\r\n")<br />    {<br />        echo "find 0 at Line {$i}\r\n";<br />    }<br />    $i ++;<br />}<br />fclose($file);<br />
Copy after login

我想问下这样性能怎么样吗,不会出现内存泄露或其他问题吧,还有进一步优化的方法吗?


------解决方案--------------------
你需要先将这个文件分割成若干个小文件 
然后循环读取每个小文件即可!
------解决方案--------------------
linux 下 $ split -b 
分割···
------解决方案--------------------
我建议你用fgets时最好制定读取的字符数,不要一行一行的读,6G的文件说不定某一行会很长!
------解决方案--------------------
6G的文本文件……

你咋能整这么大的文件?
日志应该按天或者按周、按月来记,超过一定大小就新建一个文件

应该分成多个文件
------解决方案--------------------
可以,没有问题。就是很费时间

仅就代码而言,可以缩减一点
$file_path = 'd:\work\workplace\test\file\system.log';
$file = fopen($file_path, 'r');
$key = md5(0);
$i = 1;
while ($buff = fgets($file)) {
    if ($buff == $key . "\r\n")
    {
        echo "find 0 at Line {$i}\r\n";
    }
    $i ++;
}
fclose($file);

如果一次读取的多一点(比如1M)可能要快一点。不过算法要复杂些

------解决方案--------------------
做这种东西,不是php的长项

要不搞WEB的话,还是换其它程序搞吧。

引用:
引用:

6G的文本文件……

你咋能整这么大的文件?
日志应该按天或者按周、按月来记,超过一定大小就新建一个文件

应该分成多个文件

我们公司的行为日志,一天6G
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template