Export data to CSV file in php



In many website’s admin section, import/export functionality is required, so you can get and update the records quickly as per your requirement. So today in this tutorial I will show you how to export data to CSV file in php.

You can use following code as it is if you want to export a table, you just need to change the database and table name.

<?php

// Database configs
$host="localhost";
$dbuser="root";
$dbpass="";
$dbname = "dummydb"; 

$link = mysqli_connect($host, $dbuser, $dbpass, $dbname);

if (mysqli_connect_errno())
	echo mysqli_connect_error();

// Fetch data from Database
$output = "";
$table = "sample_table";

$result = mysqli_query($link , "select * from $table");
$fields_info = mysqli_fetch_fields($result);

// For CSV header row
foreach($fields_info as $field){
	$heading = $field->name;
	$output .= '"'.$heading.'",';
}
$output .="\n";

$total_columns = count($fields_info);

// Get Data rows from the table
while ($row = mysqli_fetch_array($result)) {
	for ($i = 0; $i < $total_columns; $i++) {
		$output .='"'.$row["$i"].'",';
	}
	$output .="\n";
}

// Download the csv file
$filename = "sample_table.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

?>

This is a simple program for export data to csv file.  You can change this as per your requirement. Hope this will help you.