Home  >  Article  >  Backend Development  >  Reading a 1G file size through PHP

Reading a 1G file size through PHP

jacklove
jackloveOriginal
2018-06-08 14:29:361985browse

Reading files is very important in php. Reading files with larger memory requires certain skills. This article will explain the skills.

Since the file function reads all the contents into the memory at once, and in order to prevent some poorly written programs from taking up too much memory and causing insufficient system memory and causing the server to crash, PHP needs to Some good ideas.

01 思路1:利用php执行linux的命令,将一个文件内容(a.log)复制到另一个文件中(b.log)
cat a.log >>b.log
02 思路2:用php执行linux的head命令,获取内容,一行行写入另一个文件(b.log)中。
cat a.log|wc -l
sed -n '1 p' a.log
fileputcontents('b.log’, $content, FILE_APPEND);
//02.读取1G的文件内容
  public function testGetLarge()
  {/*{{{*/
 #01. 方法1 直接cat后重定向
  #if('useCat' == 'useCat')
 if(0 && 'useCat' == 'useCat')
 {
 `cat a.log>>b.log`;
  }
#02. 使用flie_put_contents ,一行一行读取并追加写入
 if('useFilePutContents' == 'useFilePutContents')
 {/*{{{*/
$lineNum = `cat a.log|wc -l`;
for($i=1; $i<= $lineNum; $i++)
 {
   $content = `sed -n &#39;$i p&#39; a.log`;
   //文件追加
   file_put_contents(&#39;b.log&#39;, $content, FILE_APPEND);
   }
   }/*}}}*/

This article explains in detail how to read a 1G file size through PHP. For more related knowledge, please pay attention to the PHP Chinese website.

Related recommendations:

Explain PHP class initialization function code

Explain PHP object-oriented, PHP inheritance related code

Explain the related code of PHP object-oriented serialization and deserialization

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

Statement:
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