PHP fgetcsv() - find number of columns

末鹿安然 提交于 2019-12-04 06:46:50

If I understand, you simply need count($line), because fgetcsv() has returned an array representing one row from the CSV file. The array's count() is therefore the number of source columns.

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

Not tested, but should work!

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

edit: tested, working do fseek(0) instead of save the values in an array: will be a lot faster

Michael Berkowski answer work fine for me, but in my case, i also had to specify the csv separator in the fgetcsv() function call. It's Comma "," by default, i change it to semicolon ";". Like this:

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!