PHP CSV File Export

In this tutorial we are going to see how to export MySQL database records to a CSV file. Few days before we have seen about how to read from a CSV file.

After connecting to the database, we have to fetch MySQL table records. These database results should be formatted as CSV string with proper delimiters and enclosures. And then, we need to download CSV after sending header to the browser.

php-csv-export

View DemoDownload

Example: Export Database Records to CSV

In this example, we have a MySQL table named as toy. we are reading the field names of this table and adding them as a heading of the CSV file. And then, we are iterating table rows and write it in CSV string format.

We have to set header with content-type, disposition and file name with .csv extension to export CSV formatted string and download it as an attachment file.

<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("phppot_examples",$conn);

$query = "SELECT * FROM toy";
$result = mysql_query($query);

$num_column = mysql_num_fields($result);		

$csv_header = '';
for($i=0;$i<$num_column;$i++) {
	$csv_header .= '"' . mysql_field_name($result,$i) . '",';
}	
$csv_header .= "\n";

$csv_row ='';
while($row = mysql_fetch_row($result)) {
	for($i=0;$i<$num_column;$i++) {
		$csv_row .= '"' . $row[$i] . '",';
	}
	$csv_row .= "\n";
}
/* Download as CSV File */
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=toy_csv.csv');
echo $csv_header . $csv_row;
exit;
?>

View DemoDownload

This PHP code tutorial was published on October 23, 2014.

↑ Back to Top