How can I get the total number of rows in a CSV file with PHP?

后端 未结 10 906
后悔当初
后悔当初 2020-12-05 22:35

How can I get the total number of rows that are in a CSV file using PHP? I\'m using this method but can get it to work properly.

if (($fp = fopen(\"test.csv\         


        
相关标签:
10条回答
  • 2020-12-05 23:26

    I know that this is pretty old, but actually I ran into the same question. As a solution I would assume to use linux specific logic:

    $rows = shell_exec('$(/bin/which cat) file.csv | $(/bin/which tr) "\r" "\n" | $(which wc) -l');
    

    NOTE: this only works for linux only and this only should be used if you are 100% certain that your file has no multiline-cells

    0 讨论(0)
  • 2020-12-05 23:27

    Note; none of higher-upvoted solutions that count lines in the file are reliable, as they are only counting the lines, not the csv entries (which can contain newline characters)

    I'm using a similar solution to op, and it works perfectly, but with op's code the while part can break on empty lines, which is potentially his problem.

    So it looks like this (edited op's code)

    $rowCount=0;
    if (($fp = fopen("test.csv", "r")) !== FALSE) {
      while(!feof($fp)) {
        $data = fgetcsv($fp , 0 , ',' , '"', '"' );
        if(empty($data)) continue; //empty row
        $rowCount++;
      }
      fclose($fp);
    }
    echo $rowCount;
    
    0 讨论(0)
  • 2020-12-05 23:30

    Try

    $c =0;
    $fp = fopen("test.csv","r");
    if($fp){
        while(!feof($fp)){
              $content = fgets($fp);
          if($content)    $c++;
        }
    }
    fclose($fp);
    echo $c;
    
    0 讨论(0)
  • 2020-12-05 23:41

    In case you are getting the file from a form

    $file = $_FILES['csv']['tmp_name'];
                    $fp = new SplFileObject($file, 'r');
                    $fp->seek(PHP_INT_MAX);
                    echo $fp->key() + 1;
                    $fp->rewind();
    

    Works like charm!!!!!!!!!!!!!!!!!!

    0 讨论(0)
提交回复
热议问题