码
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在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);