我有一个脚本显示csv文件,其中包含2个colums,从google驱动器到表
<?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文件中的列数?
答案 0 :(得分: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>";
}
}