我正在尝试导出到 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);
有人有其他想法吗?
最佳答案
参见 manual
php://output is a write-only stream that allows you to write to the output buffer mechanism
in the same way as print and echo.
这真的说明了一切。
因此,当您从浏览器运行它时,标准输出机制是将其发送到浏览器
,因为这就是echo
或print
会做的做。但在 PHP CLI 模式下,它将输出发送到终端。
答案是改变这一行
$output = fopen('php://output', 'w');
到
$output = fopen($filename, 'w');
然后您只需决定是通过浏览器还是 CLI(cron 作业)和 here is a suggestion 运行
if ( php_sapi_name() !== 'cli' ) {
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=" . $filename . ".csv");
readfile($filename);
}
您将不得不使用 php_sapi_name()
检查您的系统报告的内容,以确保您正在测试正确的条件。
关于php - 在服务器上作为 cron 运行时强制下载生成的 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21044376/