2010-09-09 79 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