【问题标题】:count file lines always returns 1 - mac OSx计数文件行总是返回 1 - mac OSx
【发布时间】:2013-02-27 05:09:13
【问题描述】:

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

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

你认为这是为什么? 附带说明一下,我使用的是 Mac OSx。

谢谢

【问题讨论】:

    标签: php file count


    【解决方案1】:

    试试这个:

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

    【讨论】:

      【解决方案2】:

      来自 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.
      

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

      【讨论】:

      • 我插入了这个:ini_set("auto_detect_line_endings",true);但还是不行!!我也认为这与此有关。您还需要什么其他信息?
      【解决方案3】:

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

      $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;
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-28
        • 1970-01-01
        • 2015-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多