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 the header to the browser.

View Demo

Example: Export Database Records to CSV

In this example, we have a MySQL table named as the 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.

php-csv-export

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 = mysqli_connect("localhost","root","test", "phppot_examples");

$query = "SELECT * FROM toy";
$result = mysqli_query($conn, $query);

$num_column = mysqli_num_fields($result);		

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

$csv_row ='';
while($row = mysqli_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

Photo of Vincy, PHP developer
Written by Vincy Last updated: October 29, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).
Explore topics
Need PHP help?