[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);
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 '$i p' a.log`; 18 //文件追加 19 file_put_contents('b.log', $content, FILE_APPEND); 20 } 21 22 }/*}}}*/
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!