PHP CSV File Export Using fputcsv()

In this tutorial we are going to export MySQL records to a CSV File using PHP function fputcsv(). In previous article we have formatted the array of database results as CSV string. But by using fputcsv() function we need not format data to export it to a .csv file.

View DemoDownload

PHP fputcsv()

In this example, the fputcsv() function accepts array of database results and a file resource pointer. This array of results are converted into the CSV format and written to the target .csv file with the reference of the given file pointer. The syntax of this function is,

fputcsv($file_pointer, $input_array, $delimiter = ',', $enclosure = '"');

In this code, we are creating the file pointer by opening PHP output stream. And then, we set this pointer and database field array to the fputcsv() function. This function will be called after setting header with content-type, disposition and CSV file name. The PHP code is,

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

$filename = "toy_csv.csv";
$fp = fopen('php://output', 'w');

$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='phppot_examples' AND TABLE_NAME='toy'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
	$header[] = $row[0];
}	
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);

$num_column = count($header);		
$query = "SELECT * FROM toy";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
	fputcsv($fp, $row);
}
exit;
?>

View DemoDownload

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

↑ Back to Top