PHP:PDO + CSV导出不下载(标题问题?)

时间:2018-05-21 09:31:08

标签: php pdo export-to-csv

我很难让我的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编写了表格列标题。

2 个答案:

答案 0 :(得分:2)

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

简单地说:

1.替换

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

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

2.替换

fclose($fp);

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

这将起作用

答案 1 :(得分: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);