【问题标题】:Forcing generated CSV to download when run as cron on server在服务器上作为 cron 运行时强制下载生成的 CSV
【发布时间】: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");) 却从未使用过它

标签: php mysql csv cron centos


【解决方案1】:

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. 

这确实说明了一切。

因此,当您从浏览器运行此程序时,标准输出机制是 send it to the browser,因为这是 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() 检查系统报告的内容,以确保您正在测试正确的条件。

【讨论】:

  • 感谢您的回复!我试过使用 $output = fopen($filename, 'w');但是会发生什么是它得到了权限被拒绝的错误,我推测是因为它还没有创建,所以它找不到文件?读取文件时相同它设法在终端中运行但文件输出为空白:-(
  • 这听起来像是权限问题。检查运行 cron 的用户以及运行 Apache 的用户是否被允许在该文件夹中创建文件!
  • 原来是因为我没有定义它去一个具有权限的特定文件夹!卧槽!更改它,使其进入正确的文件夹,现在它正在正确写入!欢呼!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2011-09-03
  • 2021-11-07
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
相关资源
最近更新 更多