PHP CSV File Export

by Vincy. Last modified on October 29th, 2022.

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.


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.

$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;

View DemoDownload

Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top

Share this page