2015-11-23 49 views
0

代码Yii2 setDownloadHeaders()不工作

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

+0

好,我得到了它输出'内容Disposition'头通过把'的Yii :: $ APP->响应 - >发送();'setDownloadHeaders后'右()',但“Content-Type”标题仍然是错误的。 – Chloe

+0

有几个导出csv扩展名。使事情变得更容易,不会重新发明轮子。 –

回答

0

这是因为在第一回波PHP发送抬头,Yii的做它之前。 有一些方法可以解决问题。

  • 收集输出到缓冲区,然后发送它。

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