php – 目前我的代码将数据导出到CSV文件,并将其存储在服务器上.但是我想要它下载文件.我该怎么做呢?

我过去尝试过使用标题,但它下载了一个空的CSV文件或
PHP文件本身.

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

最佳答案 试试你可以得到你的结果.

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

?>

点赞