Yii2 setDownloadHeaders()不起作用

问题描述 投票:0回答:1

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();
  }
}

测试:

$ 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,,

它也没有在浏览器中下载CSV文件。它没有设置标题。怎么了?

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

php http-headers yii2
1个回答
0
投票

这是因为php在Yii之前发送了第一个echo的头部。有一些方法可以解决这个问题。

  • 将输出收集到缓冲区,然后发送。 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;
  • 如果输出太大而无法放入内存,则数据可能会存储到临时文件中。然后发送文件并删除临时文件。在这种情况下,无需手动设置标题。 $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);
© www.soinside.com 2019 - 2024. All rights reserved.