Return to Snippet

Revision: 30719
at August 20, 2010 01:15 by damanlovett

Initial Code

 * 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
        $results = $this->ModelName->find('all', array());

	// The column headings of your .csv file
	$header_row = array("ID", "Received", "Status", "Content", "Name", "Email", "Source", "Created");
	// 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(

Initial URL

Initial Description

Initial Title
CakePHP CSV export Controller

Initial Tags
cakephp, csv

Initial Language