How can I get the total number of rows in a CSV fi

2019-01-19 09:57发布

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

标签: php csv row totals
9条回答
看我几分像从前
2楼-- · 2019-01-19 10:58

CSV rows are separated by line breaks. Therefore, split the rows by line breaks, and you will get an array of rows, which is countable.

if (($fp = fopen("test.csv", "r")) !== FALSE) { 
    $rows = explode("\n", $fp);
    $length = count($rows);

    echo $length;
}
查看更多
甜甜的少女心
3楼-- · 2019-01-19 10:59

Try

$c =0;
$fp = fopen("test.csv","r");
if($fp){
    while(!feof($fp)){
          $content = fgets($fp);
      if($content)    $c++;
    }
}
fclose($fp);
echo $c;
查看更多
贪生不怕死
4楼-- · 2019-01-19 10:59

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!!!!!!!!!!!!!!!!!!

查看更多
登录 后发表回答