Home > Backend Development > PHP Tutorial > How to read a 1G file size in PHP

How to read a 1G file size in PHP

一个新手
Release: 2023-03-16 12:28:01
Original
1331 people have browsed it

[Background]: Since the file function reads all the contents into the memory at one time, and PHP needs to prevent some poorly written programs from taking up too much memory and causing insufficient system memory and causing the server to crash. Think of something better.

[Ideas]:


##

01 思路1:利用php执行linux的命令,将一个文件内容(a.log)复制到另一个文件中(b.log)
cat a.log >>b.log02 思路2:用php执行linux的head命令,获取内容,一行行写入另一个文件(b.log)中。
cat a.log|wc -l
sed -n '1 p' a.logfileputcontents('b.log’, $content, FILE_APPEND);
Copy after login

[Code Implementation]:


 1  //02.读取1G的文件内容 
 2  public function testGetLarge() 
 3  {/*{{{*/ 
 4      #01. 方法1 直接cat后重定向 
 5      #if('useCat' == 'useCat') 
 6      if(0 && 'useCat' == 'useCat') 
 7      { 
 8          `cat a.log>>b.log`; 
 9      }
 10 
 11      #02. 使用flie_put_contents ,一行一行读取并追加写入
 12      if('useFilePutContents' == 'useFilePutContents')
 13      {/*{{{*/
 14          $lineNum = `cat a.log|wc -l`;
 15          for($i=1; $i<= $lineNum; $i++)
 16          {
 17              $content = `sed -n &#39;$i p&#39; a.log`;
 18              //文件追加
 19              file_put_contents(&#39;b.log&#39;, $content, FILE_APPEND);
 20          }
 21 
 22      }/*}}}*/
Copy after login

The above is the detailed content of How to read a 1G file size in PHP. For more information, please follow other related articles on the PHP Chinese website!

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