2010-09-09 75 views

回答

3

您可以使用fopen打开文件,使用fgets读取这些行。

$fh = fopen("file", "r"); // open file to read. 

while (!feof($fh)) { // loop till lines are left in the input file. 
     $buffer = fgets($fh); // read input file line by line. 
     ..... 
     }  
}  

fclose($fh); 
6

除非您需要在同一时刻处理所有数据,否则可以分段读取它们。例如,对于二进制文件:

<?php 
$handle = fopen("/foo/bar/somefile", "rb"); 
$contents = ''; 
while (!feof($handle)) { 
    $block = fread($handle, 8192); 
    do_something_with_block($block); 
} 
fclose($handle); 
?> 

上面的例子可能会破坏多字节编码(如果有跨8192字节边界多字节字符 - 例如在UTF-8 Ǿ),所以对于具有有意义endlines文件(例如文字),试试这个:

<?php 
$handle = fopen("/foo/bar/somefile", "rb"); 
$contents = ''; 
while (!feof($handle)) { 
    $line = fgets($handle); 
    do_something_with_line($line); 
} 
fclose($handle); 
?> 
+1

据我所知,如果文件的编码没有兼容ASCII的单字节行结束符,fgets()'仍然会搞乱它。 UTF-16。 – scy 2014-11-07 15:28:07