2013-02-27 19 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; 

我喜欢第二个代码,如果我想知道在特定的文件中只行