Return to Snippet

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


Initial Code
<?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);
}
?>

Initial URL
http://gist.github.com/535882

Initial Description


Initial Title
CakePHP CSV export Controller

Initial Tags
cakephp, csv

Initial Language
PHP