dongsha2792
2011-10-06 17:36 阅读 59
已采纳

PHP fgetcsv() - 查找列数

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

Here's my script, which is only utilizing the first column, but I'm running slightly blind. I want to place a variable that limits the column count. (since I may make a mistake and add a column, or even miss 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."
";
}

fclose($file);
?>

I'm sure it's one of those easy easy things that I'm not getting.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    dsfsd43523 dsfsd43523 2011-10-06 17:38

    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."
    ";
    }
    
    点赞 评论 复制链接分享
  • dongyou9721 dongyou9721 2011-10-06 17:45

    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

    点赞 评论 复制链接分享
  • dsffds54654 dsffds54654 2015-08-12 16:04

    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, ';')){

    点赞 评论 复制链接分享

相关推荐