我正在将 CSV 文件导入我的数据库。我想用列显示前 5 行,以便了解文件中的内容。所以下面我制作了一个快速脚本来打开文件。我计算列数,遍历列数,为每个列创建,然后在其下方抛出一个 while() 循环,以显示行。当然,我循环遍历要匹配的列数。
我成功地从文件中获取数据,我什至得到了正确的列数。但它显示的是文件中间某处的结果,而不是前 5 条记录。
第一行帮助我了解列的名称(如果有列名)。
脚本很脏,我很好奇如何优化它。
<?
$filerow = $numcols =0;
if(is_file($targetDirectoryFile)){
$file_opened = fopen($targetDirectoryFile, "r"); // open the file
?>
<table class="itemstable" style="width:100%;">
<?
$getfileInfo = fgetcsv($file_opened);
$numcols = count($getfileInfo); // count columns
?>
<tr>
<? for($cols = 0; $cols < $numcols; $cols++ ){ // loop thru # of columns ?>
<th>Column <?=$cols+1;?></th>
<? } ?>
</tr>
<?
// feels like this could be done better.
while ($getfileInfo2 = fgetcsv($file_opened)){
$filerow++;
?>
<tr>
<? for($col = 0; $col < $numcols; $col++ ){ // loop thru # of columns ?>
<td><?=trim($getfileInfo2[$col]);?></td>
<? } ?>
</tr>
<?
if($filerow > 4){ break; fclose($file_opened); // stop and close after 5 loops }
}
echo '</table>';
//fclose($file_opened);
}
?>