php - 在服务器上作为 cron 运行时强制下载生成的 CSV

标签 php mysql csv cron centos

我正在尝试导出到 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. 

这真的说明了一切。

因此,当您从浏览器运行它时,标准输出机制是将其发送到浏览器,因为这就是echoprint 会做的做。但在 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/

相关文章:

MySQL:打印计数值

mysql - 语句更改时在 SQL 上获取数据

powershell - 使用 Import-CSV 时转换数据类型

php - Laravel - Livewire,如何自定义全局消息URL?

php - PHP 和 iOS 中的河豚算法

php - 处理两个 $_POST 时出现警告 : array_merge(): Argument #1 is not an array,

python - 如何在 Python 中拆分数字后显示前导零

php - jQuery UI TABS + AJAX + PHP 动态内容加载

mysql - 如何将重复数据值分组到我的脚本中

Java - 从第二行开始读取文本文件