【发布时间】:2014-09-22 11:18:19
【问题描述】:
我编写了以下脚本,该脚本用于根据数据库中的内容创建 CSV 文件。该脚本本身可以完美运行并创建 CSV 文件并按预期填充它。问题是当文件自动下载时它是空的,但是当通过 FTP 从托管服务器下载它时,它会充满信息。
在文件成功写入之前文件是否刚刚下载?有什么办法可以解决这个问题吗?
<?php
// Establish the MySQL Database Connection
include_once("./include/database.php");
include("functions.php");
$filename = 'devices.csv';
$headers = array('ID', 'Device', 'Name', 'Type', 'Scope', 'OS', 'Datacenter');
$handle = fopen($filename, 'w');
fputcsv($handle, $headers, ',', '"');
$sql = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);
while($results = mysql_fetch_object($sql))
{
$type = getDeviceType($results->type, $dp_conn);
$scope = getDeviceScope($results->scope, $dp_conn);
$os = getOS($results->os, $dp_conn);
$datacenter = getDatacenter($results->datacenter, $dp_conn);
$row = array(
$results->id,
$results->device_id,
$results->name,
$type,
$scope['name'],
$os,
$datacenter
);
fputcsv($handle, $row, ',', '"');
}
// rewind the "file" with the csv lines
fseek($handle, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
// make php send the generated csv lines to the browser
fpassthru($handle);
fclose($handle);
?>
【问题讨论】:
标签: php mysql csv download dynamically-generated