Search code examples
phpcsvdownloadexportfputcsv

Currently my code exports data to a CSV file, and stores it on the server. But I want it to download the file. How do I do this?


I tried doing it with headers in the past, but it either downloaded an empty CSV file or the PHP file itself.

<?php
    $database = new PDO('mysql:host=localhost;dbname=DB_Name', "root", "");

    $sql = "SELECT Card_ID, Card_UID, Card_Type FROM cards";

    $stmt = $database->prepare($sql);
    $stmt->execute();

    $filename = 'MyCSVFile-'.date('Y-m-d').'.csv';

    $data = fopen($filename, 'w');

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($data, $row);
    }
    fclose($data);
?>


Solution

  • Try like that you can get your result.

    <?php
    $database = new PDO('mysql:host=localhost;dbname=DB_Name', "root", "");
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    
    $sql = "SELECT Card_ID, Card_UID, Card_Type FROM cards";
    
    $stmt = $database->prepare($sql);
    $stmt->execute();
    
    $data = fopen('php://output', 'w');
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($data, $row);
    }
    fclose($data);
    

    ?>