0

我有一个脚本,它显示从谷歌驱动器到表格的 2 个列的 csv 文件

 <?php
            // Connection class for parsing CSV file
            require_once "FGetCSV.php";
            $shs = new File_FGetCSV;

            // Open the CSV file to Google Drive
            $cfg_File = 'link to csv file in gd';
            $f = fopen($cfg_File, "r") or die("Can not open \"$cfg_File\" - ".$php_errormsg);

            // Output CSV file as a table
            $out[]="<table class=\"tb\">";

            $i = 0;
            while ($data = $shs->fgetcsv($f, 65536, ",")) {
                $i++;
                if ($i == 1) {
                    $out[] = "<thead><tr>";
                    $out[] = "<td class=\"header-tb\">$data[0]</td><td class=\"header-tb\">$data[1]</td>";
                    $out[] = "</tr></thead><tbody>";
                }
            else {
            $out[] = "<tr>";
            $out[] = "<td>$data[0]</td><td>$data[1]</td>";
            $out[] = "</tr>";
            }
            }
            $out[] = '</tbody></table>';
            fclose($f);
            echo implode('',$out);
 ?>

如何改进脚本以便确定 csv 文件中的列数?

4

1 回答 1

3

所以要动态检测列大小

$i = 0;
$columns = 0;
while ($data = $shs->fgetcsv($f, 65536, ",")) {
  $i++;
  if ($i == 1) {
    $columns = count($data);
    $out[] = "<thead><tr>";
    // iterate over columns
    for($c=0;$c<$columns;$c++) {
      $out[] = "<td class=\"header-tb\">".$data[$c]."</td>";
    }
    $out[] = "</tr></thead><tbody>";
  }
  else {
    $out[] = "<tr>";
    // iterate over columns
    for($c=0;$c<$columns;$c++) {
      $out[] = "<td>".$data[$c]."</td>";
    }
    $out[] = "</tr>";
  }
}
于 2012-09-11T12:18:47.583 回答