Skip to content
Advertisement

How to create download popup (headers) for csv file with file_put_contents php

I was wondering if someone could give me some pointers on how to create a download popup as well as a location for the user to save it.

So when they click on my “Download as CSV” button, it’ll give the user a prompt to select a destination in their directory.

Currently, I’m able to get a file downloaded working, but it’s only if I run it from my command line. I’m not too sure how to implement headers with this.

The main issue is because I can’t use fopen(), fwrite(), and fclose() because I’m adding only a single (albeit BIG) string to the csv file.

Here’s some code that works only if I run the program locally.

  $output = print_r(cleanUpEntry($info), true);
  file_put_contents("output.csv", $output);

It downloads the file to the same exact folder as my PHP file, but I need it to work on a webpage so that the user can download the file.

Note* I can’t use fputcsv since it only works for arrays, and mine is a multidimensional array, so it’s much easier to just get the output of print_r.

Advertisement

Answer

Send CSV file to the browser

$output = ...
header('Content-Type: text/csv');
echo $output;
exit;

Browsers tend to open files like CSVs, PDFs etc. To save the file instead of opening, add HTTP header Content-Disposition. For files larger few bytes, use Content-Length as well.

Force browser to download file.

$output = ...
$filename = "output.csv";
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header("Content-Length: " . strlen($output));
echo $output;
exit;

Send static file to the browser

Your web server (Apache, Nginx etc.) should handle static files, but in case you need to run it thru PHP for security or other reasons…

$file = './files/myfile.csv';
header('Content-Type: text/csv');
readfile($file);
exit;

Force browser to download a static file.

$file = './files/myfile.csv';
$filename = basename($file); // or specify directly, like 'output.csv'
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header("Content-Length: " . filesize($file));
readfile($file);
exit;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement