计数文件行总是返回1 - mac OSx


count file lines always returns 1 - mac OSx

我是php新手。我试图计算txt文档的行数,但这总是返回1(尽管文件中有更多的行):

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

你认为这是为什么?顺便说一句,我用的是Mac OSx。

谢谢

试试这个:

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

从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.

那可能是它的原因。没有更多的信息很难说。

这将使用更少的内存,因为它不会将整个文件加载到内存中:

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

fgets将单行加载到内存中(如果省略第二个参数$length,它将继续从流中读取,直到到达行尾,这正是我们想要的)。如果您关心运行时间和内存使用情况,那么这仍然不可能像使用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;

如果我只想知道特定文件

中的行,我更喜欢第二个代码