使用PHP导出数据后下载的文件为空

时间:2016-05-16 09:56:34

标签: php pdo

我有这个PHP脚本来更新MySQL db的特定表:

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../connection/connect.php');

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.csv");
header("Pragma: no-cache");
header("Expires: 0");

$sql = "SELECT * FROM patient";
$stmt = $conn->prepare($sql);

$stmt->execute();
//var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('backup.csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    // Export every row to a file
    fputcsv($data, $row);
}
?>

我在同一目录中创建了一个名为backup.csv的文件,每次执行此脚本时数据都会正确更新。但问题是我无法在.csv文件中的表格中添加标题。

下载的文件为空。我需要下载backup.csv而不是reports.csv

我试过了:

header("Content-Disposition: attachment; filename="'.$data.'";");

但它没有帮助。该文件仍为空。

2 个答案:

答案 0 :(得分:2)

您应该在fclose($data);之后立即while loop。我建议您在执行查询代码后使用headers。请尝试/查看以下示例代码。

示例

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../connection/connect.php');

$sql = "SELECT * FROM patient";
$stmt = $conn->prepare($sql);

$stmt->execute();
//var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('backup.csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    // Export every row to a file
    fputcsv($data, $row);
}
// Closing the file
fclose($data);


header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=backup.csv");
header("Pragma: no-cache");
header("Expires: 0");
?>

答案 1 :(得分:2)

您的问题是您实际上没有发送您创建的文件。

这是一个更好的结构,但请记住,您还必须将您构建的文件发送到浏览器

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../connection/connect.php');

$sql = "SELECT * FROM patient";
$stmt = $conn->prepare($sql);

$stmt->execute();

$data = fopen('backup.csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    // Export every row to a file
    fputcsv($data, $row);
}
fclose($data);                 // <- close file

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('backup.csv');        // <- new line
?>