Background: I have a table on the website that users can select rows from and then click an export button to download a .csv of those rows.
I'm creating an array of arrays from the table on the front-end and passing the array via AJAX to a PHP script that is using fputcsv() to put them in .csv format. I'm able to echo the result, as well as push the results to a .csv file on the server, and both display correctly. But for whatever reason I can't get the browser to offer the file for download.
I've referenced quite a few stackoverflow articles as well as done research into HTTP headers and nothing seems to do the trick.
My code is pasted below:
<?php
// this is the array of arrays passed via AJAX
$gaps = $_POST["gaps"];
function array_to_csv_download($array, $filename='export.csv', $delimiter=",") {
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="'.$filename.'";');
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
array_to_csv_download($gaps, 'gaps.csv');