2013-02-27 69 views
0

我是新來的php。 我想指望一個txt文檔線,但始終返回我1(儘管有文件中的很多線):計數文件行總是返回1 - mac OSx

<?php 
    $file = "example.txt"; 
    $lines = count(file($file)); 
    print "There are $lines lines in $file"; 
?> 

爲什麼你認爲這是什麼? 請注意,我使用的是Mac OSx。

由於

回答

0

嘗試這種情況:

$file = "example.txt"; 
$linecount = 0; 
$handle = fopen($file, "r"); 
while(!feof($handle)){ 
    $line = fgets($handle); 
    $linecount++; 
} 

fclose($handle); 

echo $linecount; 
0

從PHP手冊(http://www.php.net/manual/en/function.file.php):

Note: If PHP is not properly recognizing the line endings when reading files 
either on or created by a Macintosh computer, enabling the auto_detect_line_endings 
run-time configuration option may help resolve the problem. 

這可能是它的原因。很難說沒有更多的信息。

+0

我插入了這個:ini_set(「auto_detect_line_endings」,true);但仍然不起作用!我也認爲這與此有關。你還需要什麼其他信息? – user2113919 2013-02-27 05:37:44

0

這將使用較少的內存,因爲它沒有整個文件加載到內存:

$file="largefile.txt"; 
$linecount = 0; 
$handle = fopen($file, "r"); 
while(!feof($handle)){ 
    $line = fgets($handle); 
    $linecount++; 
} 

fclose($handle); 

echo $linecount; 

與fgets加載一行到內存(如果省略第二個參數$長度也將繼續從閱讀流直到它到達線的末尾,這就是我們想要的)。如果你關心牆上的時間以及內存使用情況,這還不如使用PHP以外的其他東西那麼快。

唯一的危險是如果任何行很長(如果遇到沒有換行符的2GB文件,該怎麼辦?)。在這種情況下,你最好做在塊啜之,計數結束行字符:

$file="largefile.txt"; 
$linecount = 0; 
$handle = fopen($file, "r"); 
while(!feof($handle)){ 
    $line = fgets($handle, 4096); 
    $linecount = $linecount + substr_count($line, PHP_EOL); 
} 

fclose($handle); 

echo $linecount; 

我喜歡第二個代碼,如果我想知道在特定的文件中只行