【发布时间】:2014-01-10 21:23:42
【问题描述】:
我正在尝试导出到 CSV 脚本,以便在作为 cronjob 运行时下载到服务器,但仍然可以通过网络工作。
当我从 Web 运行脚本时,它会强制下载 CSV,这很棒,但是当我在服务器(CentOS 服务器)上运行它时,它只会回显文件内容。
我需要它来将文件下载到 cronjob 中定义的区域。
//OK lets export
include("config.php");
$table = "data";
$filename = "Export_" . date("Y-m-d_H-i");
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=" . $filename . ".csv");
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('artist', 'title', 'presenter', 'timeplayed'));
// fetch the data
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db('prs');
$rows = mysql_query('SELECT * FROM '.$table.' WHERE timeplayed >= NOW() - INTERVAL 24 HOUR ORDER BY id DESC');
if($rows === FALSE)
{
die(mysql_error());
}
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
有人有其他想法吗?
【问题讨论】:
-
你为什么不用
SELECT ... INTO OUTFILE? -
在 cron 脚本中使用
headers()毫无意义 - 因为没有浏览器可供下载:这就是在不试图理解它实际在做什么的情况下剪切和粘贴别人的代码所带来的.... 为什么不写入实际的文件系统文件名而不是php://output?你甚至定义了一个文件名 ($filename = "Export_" . date("Y-m-d_H-i");) 却从未使用过它