0

我正在将 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);
}
?>
4

1 回答 1

0

至于优化,您只需使用以下命令即可摆脱if循环中的语句:

while ( ($getfileInfo2 = fgetcsv($file_opened)) && ($filerow < 5) )
{

我也认为您的文件没有正确关闭,因为您将语句放在语句之后break,但我不明白这会如何导致您遇到的问题。

关于中间的输出;输入文件和生成的 html 是什么样的?

于 2011-10-07T22:19:47.840 回答