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

82,056

Solution 1

Here's another option using file() to read the entire file into an array, automatically parsing new lines etc:

$fp = file('test.csv');
echo count($fp);

Also, since PHP5, you can pass in the FILE_SKIP_EMPTY_LINES... to skip empty lines, if you want to:

$fp = file('test.csv', FILE_SKIP_EMPTY_LINES);

Manual: http://php.net/manual/en/function.file.php

Solution 2

Create a new file reference using SplFileObject:

$file = new SplFileObject('test.csv', 'r');

Try to seek to the highest Int PHP can handle:

$file->seek(PHP_INT_MAX);

Then actually it will seek to the highest line it could in the file, there is your last line and the last line + 1 is equals to your total lines:

echo $file->key() + 1;

Tricky, but this will avoid you from loading the file contents into memory, which is a very cool thing to do when dealing with really large files.

Solution 3

Try

$c =0;
$fp = fopen("test.csv","r");
if($fp){
    while(!feof($fp)){
          $content = fgets($fp);
      if($content)    $c++;
    }
}
fclose($fp);
echo $c;

Solution 4

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

Solution 5

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;
Share:
82,056
telexper
Author by

telexper

Updated on July 25, 2022

Comments

  • telexper
    telexper almost 2 years

    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", "r")) !== FALSE) { 
      while (($record = fgetcsv($fp)) !== FALSE) {
          $row++;
      }
    
      echo $row;
    }
    
  • Tan Hong Tat
    Tan Hong Tat over 10 years
    This works for small file. If you have a huge CSV file (GB size), using file() to read the entire file and count() is probably a bad idea, because it stores the file in memory, and may hang a low memory system.
  • xd6_
    xd6_ over 9 years
    @TanHongTat is there a more efficient way to do this?
  • scrowler
    scrowler over 9 years
    @xd6_ this answer would be more efficient for large files
  • JeopardyTempest
    JeopardyTempest almost 7 years
    Brilliant, works great, this should be the top answer.
  • Vlad Preda
    Vlad Preda almost 7 years
    Works with PHP >= 5.1 - and is memory efficient. Use $file->rewind() to go back to the start of the file.
  • Alex Skrypnyk
    Alex Skrypnyk almost 7 years
    Just be aware that there is no easy way to do all this that would cover 100% of cases simple because the value of CSV column may contain new line character. This means that to get true number of 'records' in the file you would actually have to parse the file.
  • ρяσѕρєя K
    ρяσѕρєя K almost 7 years
    Add some explanation with answer for how this answer help OP in fixing current issue
  • Pete - iCalculator
    Pete - iCalculator almost 6 years
    The best answer here
  • Bill Garrison
    Bill Garrison about 5 years
    the only problem i have with this answer is that on my very first test the csv file had a blank line at the end....which threw off everything. Is there a workaround like the above "FILE_SKIP_EMPTY_LINES"
  • Leo Cavalcante
    Leo Cavalcante about 5 years
    @BillGarrison, please try: $file->setFlags(SplFileObject::SKIP_EMPTY)
  • Bill Garrison
    Bill Garrison about 5 years
    @LeoCavalcante I ended up having to use this combination of flags to get it to work (on windows) $file->setFlags(SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
  • Steve Horvath
    Steve Horvath over 4 years
    Similar problem to the previous "solution" that loads up the whole file: you'll only count physical rows, and a csv file can easily contain newlines that are part of the content; so the result will be skewed.
  • scrowler
    scrowler over 4 years
    Isn't this essentially the same as this answer from two years ago?
  • Steve Horvath
    Steve Horvath over 4 years
    Thanks, @Robbie Averill to be honest, I'm not sure if it would lead to the same result in all circumstances - most notably, empty lines. I've a feeling that the other answer would simply count empty lines, while this one definitely won't. Shame on me for skipping reviewing the negative-rated answers, it's indeed reasonably close.
  • mickmackusa
    mickmackusa over 3 years
    I'd probably upvote this if there was an explanation. I have a policy against upvoting snippet dumps -- even if they are helpful/good.
  • Bokili Production
    Bokili Production about 2 years
    Well done. Very fast function, even 3 times faster than classic counting with fgets($fp).
  • Whip
    Whip about 2 years
    That's a stupid policy. However I won't upvote this because it's already answered 3 years prior.