Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 228
Samuel Stiles Avatar asked Jun 29 '13 22:06

Samuel Stiles


People also ask

How do I download a CSV file from PHP?

Try... csv download. <? php mysql_connect('hostname', 'username', 'password'); mysql_select_db('dbname'); $qry = mysql_query("SELECT * FROM tablename"); $data = ""; while($row = mysql_fetch_array($qry)) { $data . = $row['field1'].

How do I download CSV data?

Export data to a text file by saving itGo to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).


1 Answers

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);
?>
like image 182
Axel Amthor Avatar answered Oct 24 '22 00:10

Axel Amthor