Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Automatically Download CSV file in PHP

Automatically downloading a CSV file with PHP takes a particularly different structure of Code that would be present in the general creation of files. To download CSV files, the header() function and the php://output parameter must be used. This tutorial we broke down into three parts to show the importance of each code snippet.

Setting the header function

Setting the headers of the HTTP request is of extreme importance when downloading files automatically. It instructs the browser with specific options that are different from your standard HTTP request. Ensure the header() function is called to and the parameters as set out below are used.

One of the particularly important options is in the second line of code, the filename option. This is where you want to name the file that will be generated and downloaded.

PHP Code

// Set the content type 
header('Content-type: application/csv');
// Set the file name option to a filename of your choice.
header('Content-Disposition: attachment; filename=myCSV.csv');
// Set the encoding
header("Content-Transfer-Encoding: UTF-8");

Populating the CSV

Next, rather than writing to an actual file name, this parameter of fopen() giving us access to PHP’s output buffer.

PHP Code

$f = fopen('php://output', 'a'); // Configure fopen to write to the output buffer

Writing data and starting the download

With the last two sections implemented into our code, we can add some dummy data to be written. Finally, we close the virtual file and the download will subsequently start.

PHP Code

// Write to the csv
fputcsv($f, ["cell1", "cell2", "cell3"]);

// Close the file
fclose($f);
// ... download will start

All together now

Now, if we put all the syntax together, we should have a snippet of code like below.

PHP Code

// Set the content type
header('Content-type: application/csv');
// Set the file name option to a filename of your choice.
header('Content-Disposition: attachment; filename=myCSV.csv');
// Set the encoding
header("Content-Transfer-Encoding: UTF-8");

$f = fopen('php://output', 'a'); // Configure fopen to write to the output buffer

// Write to the csv
fputcsv($f, ["cell1", "cell2", "cell3"]);

// Close the file
fclose($f);
// ... download will start

The post Automatically Download CSV file in PHP appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

Automatically Download CSV file in PHP

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×