How to Create and Download CSV File in PHP

On 6/08/2018

Hi! Here we will see how to create a csv file and download it using php. CSV is one of the popular data storage methods used on the Web. Being a modern language, PHP has no problems handling various data formats including csv. It offers native functions to read and write csv files. With fputcsv() method, you can write data as a csv file and force it to download.

Clicking on a file url (link) will just open it in the browser window without downloading. The exe and zip formats are an exception here. But in case you need to download it directly to client's hard disk, then you have to make use of the readfile() function.

Let's see how to do it.

php create download csv file

PHP - Create CSV File:

The following snippet creates a csv file named 'myfile.csv' on your current working directory.

<?php
// data array
$user = array(1, 'Johnson', 'johnson@mydomain.com', 'Miami');
// filename
$filename = 'myfile.csv';

// write to csv file
$fp = fopen($filename, 'w');
fputcsv($fp, $user);
fclose($fp);
?>

Okay! We have created the csv file. Next we'll move on to the download part.

Download CSV File:

As I said before, you must use readfile() along with the proper header to force download of the file. Here's the code to do it,

<?php
// download file
header('Content-type: text/csv');
header('Content-disposition:attachment; filename="'.$filename.'"');
readfile($filename);
?>

Sending the header along with the download option will force open the 'Save File' dialog in the user's browser window.

We have used two header() functions in the above script.

The first one sets the MIME type of the content sent. Since it is 'text/csv' for csv data, we need to set it as the 'Content-type'.

The second line provides the filename to be used for storing and force the browser to display the save dialog.

Read Also:

That explains how to create csv file and automatically download it in php. I hope you find this post useful. Please share it on social media if you like it.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *