Create Downloadable CSV file from Array in PHP
In this tutorial, we are gonna teach you how to create dynamic csv file from array in PHP, which downloads in your browser just as some normal csv would do.
First of all, you need to prepare your data in a 2d array. For example:
$data_to_download = array( array("Title", "Description", "Comments"),array("Dummy Title", "Dummy Description", "Dummy Comment Count"),array("Dummy Title 2", "Dummy Description 2", "Dummy Comment Count 2"));
The secret now is in the headers. Your PHP script needs to send the headers, informing the browser that the upcoming data will be of csv data type.. So buddy.. handle it accordingly.
Browser, since already smart.. knows what to do when certain headers are sent.
So Here are the basic headers you need to send if your csv file needs to be downloaded as an attachment:
Notice the Content-Disposition:attachment; part?
It instructs the browser to treat the upcoming data as attachment and should not be shown inside the browser tab.
Here is the complete for basic csv downloading:
PS. Share if you find it useful and spread the love