Building CSV with array

后端 未结 3 1730
借酒劲吻你
借酒劲吻你 2020-12-29 15:12

I need to run a query that will return multiple rows and export it to a CSV. I have to put the cells in a certain order though.

So lets say my table is laid out id,

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 16:10

    Here's some code I use... you could adjust the columns you need in the export...

    Note: This CSV is directly sent to php://output which writes directly to the output buffer. This means you're not saving any .csv files on the server and it can handle a much larger file size that building a giant array and then trying to loop through it.

        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=\"Jobs_".date('M.j.y', $from)."-".date('M.j.y', $to).".csv\"");
        header("Pragma: no-cache");
        header("Expires: 0");
    
        $handle = fopen('php://output', 'w');
        fputcsv($handle, array(
            'JobId',
            'Template',
            'Customer',
            'Status',
            'Error',
            'PDF',
            'Run Time',
            'Wait Time',
            'Server'
        ));
    
        foreach ($jobs as $jobData) {
            fputcsv($handle, array(
                $job->getId(),
                $job->getTemplate(),
                $jobData['customers_firstname'].' '.$jobData['customers_lastname'],
                $status,
                $error,
                $jobData['products_pdfupload'],
                $job->getRunTime(),
                $job->getWaitTime(),
                $jobData['server']
            ));
        }
    
        fclose($handle);
        exit;
    

    This should give you a good mental picture of how a CSV export works. I don't use CodeIgniter's file download helper, so I can't help you on that front.

提交回复
热议问题