[英]Zend Framework 2 - Rendering CSV data
我有一個模型,它返回帶有 id、名稱、價格等的汽車數據。所以我有一個汽車控制器和一個從模型中獲取這些數據的 csv 操作:
$carTable = $this->getServiceLocator()->get('Application\Model\DbTable\Cars');
$cars = $carTable->fetchAll();
我需要將此“$cars”數據下載為 CSV 文件,以便用戶可以將其存儲在磁盤上。
我試圖禁用布局並回顯 CSV 字符串並設置“內容類型”和其他標題,但它沒有立即可用。 然后我想我應該創建一個自定義的 CsvRenderer 並在配置中注冊它。
由於我在 ZF2 站點或博客和 Stackoverflow 答案中找不到任何關於此的文檔,我想知道這是否是在 ZF2 中將數據下載為 CSV 的推薦通用方法? 還是有我不知道的更簡單的解決方案?
謝謝
一種解決方案是直接從控制器返回一個 Response 對象。
像這樣的事情很有可能起作用:
public function downloadAction()
{
// magically create $content as a string containing CSV data
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-Type', 'text/csv');
$headers->addHeaderLine('Content-Disposition', "attachment; filename=\"my_filen.csv\"");
$headers->addHeaderLine('Accept-Ranges', 'bytes');
$headers->addHeaderLine('Content-Length', strlen($content));
$response->setContent($content);
return $response;
}
(請注意,我尚未測試此代碼,但已根據注釋進行了更新!)
既然我們在談論 ZF2,我寧願通過添加一個新的 CSV ViewStrategy/Renderer/ViewModel 來解決這個問題。
您可以在此處閱讀有關實施自己的渲染和響應策略的更多信息: Zend Docs
甚至在這里:http: //zend-framework-community.634137.n4.nabble.com/ZF2-Implementing-custom-renderer-strategy-td4655896.html
這將使控制器中的代碼更精簡、更清晰、更清晰,因為您不必關心控制器中的標題,而是在渲染器中。 然后,每次您需要一個新的 CSV 輸出時,您不必重新編寫該操作,您只需使用 CSV 視圖模型
這是基於 Rob 提供的答案。
在 Rob 的回答中,通過將$response->getHeaders()
分配給新的$headers
變量,然后將->addHeaderLine
應用於該新變量,它沒有正確設置$response
上的標頭。 因此,當返回時,標頭未附加到響應中。
要解決此問題,只需將標頭直接添加到$response
如下所示:
public function downloadAction()
{
// magically create $content as a string containing CSV data
$response = $this->getResponse();
$response->getHeaders()
->addHeaderLine('Content-Type', 'text/csv')
->addHeaderLine('Content-Disposition', "attachment; filename=\"my_filen.csv\"")
->addHeaderLine('Accept-Ranges', 'bytes')
->addHeaderLine('Content-Length', strlen($content));
$response->setContent($content);
return $response;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.