Skip to content

Instantly share code, notes, and snippets.

@richardsession
Created August 18, 2010 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardsession/535882 to your computer and use it in GitHub Desktop.
Save richardsession/535882 to your computer and use it in GitHub Desktop.
Dynamically generates a .csv file by looping through the results of a database call in CakePHP
<?php
/**
*
* Dynamically generates a .csv file by looping through the results of a sql query.
*
*/
function export()
{
ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
//create a file
$filename = "export_".date("Y.m.d").".csv";
$csv_file = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
$results = $this->ModelName->query($sql); // This is your sql query to pull that data you need exported
//or
$results = $this->ModelName->find('all', array());
// The column headings of your .csv file
$header_row = array("ID", "Received", "Status", "Content", "Name", "Email", "Source", "Created");
fputcsv($csv_file,$header_row,',','"');
// Each iteration of this while loop will be a row in your .csv file where each field corresponds to the heading of the column
foreach($results as $result)
{
// Array indexes correspond to the field names in your db table(s)
$row = array(
$result['ModelName']['id'],
$result['ModelName']['received'],
$result['ModelName']['status'],
$result['ModelName']['content'],
$result['ModelName']['name'],
$result['ModelName']['email'],
$result['ModelName']['source'],
$result['ModelName']['created']
);
fputcsv($csv_file,$row,',','"');
}
fclose($csv_file);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment