Search code examples
phpfgetcsv

PHP fgetcsv() displaying first 5 rows


I'm importing CSV files into my database. I want to display the first 5 rows with columns, so I can get an idea of what's inside the file. So below I crafted a quick script to open the file. I count the number of columns, loop through the number of columns, create for each, and then I throw a while() loop below that, to display the rows. Of course, I loop through the number of columns to match.

I'm successfully getting data from the file, and I'm even getting the correct number of columns. But it's displaying result from somewhere in the middle of the file, rather than the first 5 records.

The first row helps me know what the columns are called, (if there are column names).

The script is dirty, and I'm curious how it can be optimized.

<?
$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);
}
?>

Solution

  • As to optimization, you can get rid of the if statement in your loop by just using:

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

    I also don't think your file gets closed correctly as you put the statement after the break statement, but I don't see how that could lead to the problem you are having.

    About the output from the middle; what do the input file and the generated html look like?