Hey there! Thanks for visiting. I’m leaving this content intact, but I’m blogging at http://conjurecode.com now. Hope to see you there.
I recently needed the ability to export data from my application in CSV format in my CakePHP application. It didn’t need to be anything fancy, mostly just a dump from a given model, which the customer could open in Excel. I’ve written it in an abstracted way. This fairly simple function takes a model name and an array of fields which should be excluded from the output, and delivers a CSV file.
Rather than allow the function to be accessed directly, I’ve made the function private, and written a public function which accesses it. This has the added benefit of reducing the need for input validation.
Here is the function call:
public function export_orders() {
$this->export_model('Order');
}
and the function itself:
private function export_model($model, $exclude = array() ) {
$records = $this->$model->find('all');
$headings = array_diff(array_keys($records[0][$model]), $exclude);
$filename = strtolower($model) . '-export-' . date('m-d-Y') . '.csv';
header("Content-type: application/text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
$h = fopen('php://output', 'w');
fputcsv($h, $headings);
foreach ($records as $record) {
foreach($exclude as $ex) unset($record[$model][$ex]);
fputcsv($h, $record[$model]);
}
fclose($h);
exit();
}