Create a CSV File for a user in PHP

前端 未结 19 2114
故里飘歌
故里飘歌 2020-11-22 11:52

I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

<
19条回答
  •  攒了一身酷
    2020-11-22 12:13

    Here is a full working example using PDO and including column headers:

    $query = $pdo->prepare('SELECT * FROM test WHERE id=?');
    $query->execute(array($id));    
    $results = $query->fetchAll(PDO::FETCH_ASSOC);
    download_csv_results($results, 'test.csv'); 
    exit();
    
    
    function download_csv_results($results, $name)
    {            
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename='. $name);
        header('Pragma: no-cache');
        header("Expires: 0");
    
        $outstream = fopen("php://output", "wb");    
        fputcsv($outstream, array_keys($results[0]));
    
        foreach($results as $result)
        {
            fputcsv($outstream, $result);
        }
    
        fclose($outstream);
    }
    

提交回复
热议问题