Export form data to Excel (CSV) in PHP


In this tutorial you are going to learn how to download an excel report after filling a HTML form.

MySQL is not used in this tutorial, just a simple example showing how to generate Excel file using core PHP functions.

Lets see the basic code here:


//give a filename
$filename = "myexcel.csv";

//set headers to download the file
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);

//set an array
$cells = array("Column1", "Column2", "Column3");

$file = fopen('php://output', 'w');            




When you run this code on a web browser, a CSV (myexcel.csv) file will immediately download with  the values given in the array $cells[].

I have used php://output stream which sends the output from Apache server to the browser.

fputcsv() – this function plays the main role in the above script, it helps us to create the CSV file from the array $cells[].
Now, lets move to the dynamic part,

Create a form in HTML, see the below (index.html):

	<form action="excel.php" method="post">
			<tr><td>Name</td><td><input type="text" name="name" /></td></tr>
			<tr><td>Email</td><td><input type="text" name="email" /></td></tr>
			<tr><td>Location</td><td><input type="text" name="location" /></td></tr>
			<tr><td>&nbsp;</td><td><input type="submit" /></td></tr>

PHP script – slightly modified from the first script (excel.php):


//give a filename
$filename = "myexcel.csv";

//set headers to download file
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);

$file = fopen('php://output', 'w');            

//set the column names
$cells[] = array('Name', 'Email', 'Location');

//pass all the form values
$cells[] = array($_POST['name'], $_POST['email'], $_POST['location']);

foreach($cells as $cell){



if you compare the first script and this one above, you can see there is a difference in $cells[]  variable which became multi-dimensional array and also I’m looping through each array using foreach()

Basically first iteration will pass the column names which is hard coded, the second iteration will pass the dynamic values from $_POST.

See the demo and download the script here:

demo download


3 thoughts on “Export form data to Excel (CSV) in PHP

Leave a Reply

Theme: Overlay by Kaira