PHP:PDO + CSV 导出未下载(headers 问题?)

PHP: PDO + CSV export not downloading (headers issue?)

我很难使我的 CSV 导出功能正常工作。
我发现了很多使用 mysqli_* 函数的例子,但我实际上使用的是 PDO,所以我不得不根据我的需要调整一些 questions/answers。
据我所知,我正在正确解析数据并将数据写入 *.csv 文件,但最后我并没有简单地从浏览器中获得任何“下载”模式。
再一次,环顾四周,我知道我的 headers 可能有某种问题,所以我请求你的帮助。

这是我的 PHP 函数片段:

function downloadAsCSV($dsn, $dbUser, $dbPsw, $options) {
    // New PDO connection.
    $pdo = pdoConnect($dsn, $dbUser, $dbPsw, $options);

    $query = ... // Not going to write it down.

    // Let's query the database, ...
    $stmt = $pdo->prepare($query);

    // Setting up the query variables here...
    [...]
    // Executing the statement...
    $stmt->execute();

    // Headers.
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Description: File Transfer');
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename='export.csv'");
    header("Pragma: no-cache");
    header("Expires: 0");

    // Let's open tbe "*.csv" file where we'll save the results.
    $fp = fopen("php://output", "w");

    if ($fp) {
        $first_row = $stmt->fetch(PDO::FETCH_ASSOC);
        $headers = array_keys($first_row);
        fputcsv($fp, array_values($first_row));
        fputcsv($fp, $headers);

        // ... fetch the results...
        $workpiecesArray = $stmt->fetchAll();

        // ... and, finally, export them.
        foreach ($workpiecesArray as $workpiece) {
            fputcsv($fp, array_values($workpiece));
        }
    }

    fclose($fp);

    // Closing the connection.
    $stmt = null;
    $pdo = null;
}

function mysqli_field_name($result, $field_offset) {
    $properties = mysqli_fetch_field_direct($result, $field_offset);

    return is_object($properties) ? $properties->name : null;
}

我从 .

中获得了灵感,写出了 table 列标题

您需要做的是打印您现在没有打印的文件。 使用 readfile 查看此示例: http://php.net/manual/en/function.header.php#example-5554

简单地说:

1.Replace

$fp = fopen("php://output", "w");

$tmpfname = tempnam("/", "");
$fp = fopen($tmpfname, "w");

2.Replace

fclose($fp);

fclose($fp);
readfile($tmpfname);
unlink($tmpfname);

这会起作用

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="export.csv"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('export.csv'));
readfile($csvFile);
exit;
`put this after` fclose($fp);