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:

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):

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

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

 

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *