简体   繁体   English

Yii2 setDownloadHeaders()无法正常工作

[英]Yii2 setDownloadHeaders() is not working

Code

public function actionExport() {
  ini_set('memory_limit','32M');
  $whileAgo = date('Y-m-d', time() - 2*24*60*60); // 7-9 seems to be the limit for # days before the 30s timeout 
  $agkn = AdGroupKeywordNetwork::find()
    ->select(['field1', 'field2', ...])
    ->where(['>', 'event_date', $whileAgo])->asArray()->each(10000);
  $dateStamp = date('Y-m-d');
  Yii::$app->response->setDownloadHeaders("stats_$dateStamp.csv", 'text/csv');
  echo 'id,ad_group_keyword_id,keyword,network_id,quality,event_date,clicks,cost,impressions,position,ebay_revenue,prosperent_revenue'.PHP_EOL;
  // flush(); // gives us 55s more // doesn't work with gzip
  foreach ($agkn as $row) {
    echo join(',', $row).PHP_EOL;
    // flush();
  }
}

Tested: 经过测试:

$ time (curl -sv -b 'PHPSESSID=ckg8l603vpls8jgj6h49d32tq0' http://localhost:81/web/ad-group-keyword-network/export | head)
...
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<
{ [8277 bytes data]
id,ad_group_keyword_id,keyword,network_id,quality,event_date,clicks,cost,impressions,position,ebay_revenue,prosperent_revenue
9690697,527322,ray ban predator,1,6,2015-11-22,0,0.00,1,5.0,,

It's not downloading a CSV file in the browser either. 它也不在浏览器中下载CSV文件。 It's not setting the headers. 它没有设置标题。 What is wrong? 怎么了?

Reference: http://www.yiiframework.com/doc-2.0/yii-web-response.html#setDownloadHeaders()-detail 参考: http : //www.yiiframework.com/doc-2.0/yii-web-response.html#setDownloadHeaders()-detail

It's because php send header at first echo, before Yii does it. 这是因为php在Yii之前先发送回显头。 There are some way to solve the issue. 有一些解决问题的方法。

  • Collect output to buffer, then send it. 将输出收集到缓冲区,然后将其发送。

      Yii::$app->response->setDownloadHeaders("stats_$dateStamp.csv", 'text/csv'); $data = 'id,ad_group_keyword_id,keyword,network_id,quality,event_date,clicks,cost,impressions,position,ebay_revenue,prosperent_revenue'.PHP_EOL; foreach ($agkn as $row) { $data .= join(',', $row).PHP_EOL; } return $data; 
  • If output is too large to fit in memory, then data may be stored to temp file. 如果输出太大而无法容纳在内存中,则数据可能会存储到临时文件中。 Then send file and delete temp file. 然后发送文件并删除临时文件。 There is no need to set header manually in this case. 在这种情况下,无需手动设置标题。

      $filePath = tempnam(sys_get_temp_dir(), 'export'); $fp = fopen($filePath, 'w'); if ($fp) { fputs($fp, ...); } fclose($fp); return Yii::$app->response->sendFile($filePath, "stats_$dateStamp.csv") ->on(\\yii\\web\\Response::EVENT_AFTER_SEND, function($event) { unlink($event->data); }, $filePath); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM