Export Data to CSV Using PHP

It is many time we need to export table data to CSV in our most of applications.
There is a simple code to export data to CSV using PHP
Export Data to CSV Using PHP

if($_GET['action'] == 'export') {

	$titlearr = array("Heading 1","Heading 2","Heading 3","Heading 3","Heading 4");

	$q = mysql_query("select field1, field2, field3. field4 from where table");

	$columns = count($titlearr);
	for ($i = 0; $i < $columns; $i++) {
		$out .= '"'.$l.'",';
	$out .="\n";
	while ($l = mysql_fetch_assoc($q)) {
		$out .='"'.$l["field1"].'",';
		$out .='"'.$l["field2"].'",';
		$out .='"'.$l["field3"].'",';
		$out .='"$'.$l["field4"].'",';
		$out .="\n";
	header("Content-type: text/x-csv");
	header("Content-Disposition: attachment; filename=reports.csv");
	echo $out;

In above code, Heading array should match with table colums to put field values exact under headings in CSV.

You might like:

Leave a Reply