4

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);
?>
MTMaas
  • 63
  • 1
  • 5

1 Answers1

2

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

?>

  • Ah, that works! Thank you. The last thing I noted is that if I have any HTML in the PHP page, it prints that in the CVS file too. I'm guessing I just have to split my HTML and PHP? – MTMaas May 12 '15 at 09:19
  • you have to put headers because by using headers you can tell the browser that this file will be downloaded, not to be opened directly in browser. – Raja Usman Mehmood May 12 '15 at 09:22