PHP fgetcsv () - find the number of columns

I am trying to determine how many columns a csv file has.

Here is my script that uses only the first column, but I'm a little blind. I want to put a variable that limits the number of columns. (since I can make a mistake, add a column or even skip a column)

<?php
$allowedColNum=5;
$batchcount=0;
$file = fopen($file_name, "r"); 
while ($line = fgetcsv($file)){
 /* I want to stop the loop if the $allowedColNum is not correct */                 
  $col = $line[0]; 
  echo $batchcount++.". ".$col."\n";
}

fclose($file);
?>

I'm sure this is one of those light easy things that I don’t get.

+5
source share
3 answers

If I understand, you just need count($line)it because you fgetcsv()returned an array representing one line from the CSV file. Thus, the array count()is the number of columns in the source.

while ($line = fgetcsv($file)){

  // count($line) is the number of columns
  $numcols = count($line);

  // Bail out of the loop if columns are incorrect
  if ($numcols != $allowedColNum) {
     break;
  }
  $col = $line[0]; 
  echo $batchcount++.". ".$col."\n";
}
+13
source

, !

$allowedColNum=5;
$batchcount=0;
$file = fopen($file_name, "r"); 
$totCols=0;
while ($line = fgetcsv($file))
if(count($line) > $totCols) $totCols = count($line);
fseek($file, 0);
while ($line = fgetcsv($file))
{
  //....
}
fclose($file);

: , do fseek (0) :

0

Michael Berkowski is responsible for the job perfectly, but in my case I also needed to specify the csv delimiter in the fgetcsv () function call. This is a comma "," by default, I change it to a semicolon ";". Like this:

while ($ line = fgetcsv ($ file, 0, ';')) {

0
source

All Articles