简体   繁体   中英

Browser not downloading file from PHP script

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');

Well, you can not download files with AJAX. Your code looks ok, the problem is on the frontend.

Because you have post values, you need a <form> to send those values. So, remove the ajax request and use a <form target="_blank" action="....."> . The target="_blank" is needed so the form opens a new window. You can have the form already generated in your code or you can generate it using document.createElement("form") and build it from the javascript code.

Check this answer for AJAX unable to download and this one for opening a new window from a form.

Also here you can find more details about how to generate a form using javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM