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, name, address, wife. I need to build a csv in the order of id, address, wife, name. I figured I could just make an array in the correct order and then make a csv with that but after an hour of googling i cant find out how to make a csv with an array.
There is fputcsv but that requires a pre-made csv. Also, i was hoping there was a codeigniter way of doing it.
public function export() {
$this->load->helper('download');
$data[1] = 'i like pie';
$data[2] = 'i like cake';
force_download('result.csv', $data);
}
I tried that but the error said the download helper file was expecting a string not an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With