CSV export only heading Arrays not Data

65 views Asked by At

I'm Trying to export & download csv file containning mysql records using following code;

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=DepReport_'.$from.'_'.$to.'.csv');

    $output = fopen('php://output', 'w');

    fputcsv($output, array('Reference',
                'Depart Date / Time',
                'Depart Terminal',
                'Depart Flight'
                )
            );

        $i = 2;
        while($rows = mysql_fetch_array($result)) {
            fputcsv($data[$i], array($rows['ReferenceNo'],          
                     date('Y-m-d',strtotime($rows['DepartDate'])).' '.$rows['DepartTime'],
                     $rows['DepartTerminal'],
                     $rows['DepartFlight']
                     )
                );
            $i++;
        }       
    fputcsv($output, $data);
    exit;

but only getting Heading Arrays but no records

Need help to fix the code.

Regards

2

There are 2 answers

0
RightClick On BEST ANSWER

what about writing out the same way while in the loop?

header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=DepReport_'.$from.'_'.$to.'.csv');

    $output = fopen('php://output', 'w');

    fputcsv($output, array('Reference',
                'Depart Date / Time',
                'Depart Terminal',
                'Depart Flight'
                )
            );

        $i = 2;
        while($rows = mysql_fetch_array($result)) {
            //change to $output so it writes lines to same handler
            fputcsv($output, array($rows['ReferenceNo'],          
                     date('Y-m-d',strtotime($rows['DepartDate'])).' '.$rows['DepartTime'],
                     $rows['DepartTerminal'],
                     $rows['DepartFlight']
                     )
                );
            $i++;
        }       
    //fputcsv($output, $data);
//don't need anymore
        exit;
0
venca On

Put your results to $output stream

while($rows = mysql_fetch_array($result)) {
        fputcsv($output, array($rows['ReferenceNo'],          
                 date('Y-m-d',strtotime($rows['DepartDate'])).' '.$rows['DepartTime'],
                 $rows['DepartTerminal'],
                 $rows['DepartFlight']
                 )
            );
    }