PHP:PDO + CSV出口不下载(头的问题?)

问题描述 投票:1回答:2

我有一个很难让我的CSV导出功能工作。 我身边很多使用mysqli_ *函数实例发现,但我实际使用的PDO,所以我不得不一些问题/答案适应我的需要。 对于我所看到的,我在正确的解析和写入数据的* .csv文件,但最后我不只是得到任何“下载”,从浏览器模式的。 同样,环顾四周,我明白我可能有某种问题,我的头,所以我要求你的帮助。

这是我的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;
}

我已经采取的灵感来自this answer写表列标题。

php pdo export-to-csv
2个回答
2
投票

什么,你需要做的是要打印的文件,这你不这样做,现在。使用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);

而这将工作


1
投票
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);
© www.soinside.com 2019 - 2024. All rights reserved.