简体   繁体   中英

How do I prompt the user to download a PHP-generated .CSV file, and how should I handle deleting it?

Here's my PHP code to create a .CSV file based on some SQL data. It's working as intended, the only issue being that it simply creates a .CSV file on the server, and doesn't prompt the user to download it .

<?php
    require_once "../assets/repository/mysql.php";

    $query = "SELECT * FROM datashep_AMS.COMPLETE_APPLICATIONS";
    $results = mysql_query($query);

    $first = true;

    $out = fopen('export.csv', 'w');

    while($row = mysql_fetch_assoc($results)){
        if($first){
            $titles = array();
            foreach($row as $key=>$val){
                $titles[] = $key;
            }
            fputcsv($out, $titles);
            $first = false;
        }
        fputcsv($out, $row);
    }

    fclose($out);
?>

So my question is, how do I make the user download the file immediately upon it being generated?

And, once they've downloaded it (or declined), how should I handle deleting the .CSV file from my server?

no need to store anything on the server (and thus no need to delete ...). Just write the results back to the browser and set the headers accordingly:

<?php
require_once "../assets/repository/mysql.php";

$query = "SELECT * FROM datashep_AMS.COMPLETE_APPLICATIONS";
$results = mysql_query($query);

$first = true;

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="export.csv"');
header('Cache-Control: max-age=0');

$out = fopen('php://output', 'w');

while($row = mysql_fetch_assoc($results)){
    if($first){
        $titles = array();
        foreach($row as $key=>$val){
            $titles[] = $key;
        }
        fputcsv($out, $titles);
        $first = false;
    }
    fputcsv($out, $row);
}

fclose($out);
?>

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