[英]download csv file with php
我有一個帶代碼的csv文件:
// put data to file
$file = 'file.csv';
$fp = fopen($file, 'w');
foreach ($excel as $fields) {
fputcsv($fp, $fields);
}
//單擊按鈕時下載文件:
if ($this->request->getPost('cvs')) { {
if (file_exists($file)) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=' . ($file));
header('Pragma: no-cache');
readfile('/var/www/admin/backend/public/' . $file);
// OR readfile($file);
}
}
file.csv中的數據(publuc文件夾中的file.csv):
[Time,A1,A7,A30
03/24/2015,42531,130912,315805
03/25/2015,41124,132746,319098
03/26/2015,41050,134858,320934
03/27/2015,38687,134679,321747]
但是,當我單擊按鈕下載文件時,下載的文件中的數據就是頁面的全部html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"">...etc..
如何解決? 非常感謝!
有點晚了,但我想每個人都錯過了phalcon標簽。 所缺少的是
$this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);
這是我的處理方法。
$this->response->resetHeaders();
$this->response->setHeader('Content-Type', 'application/csv');
$this->response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
$this->response->setContent($content);
return $this->response;
$ content-對我來說,這是一個由數組組成的字符串,但您也可以使用file_get_contents()
我需要更多信息來肯定地回答,但這聽起來像只是將瀏覽器配置為將這種類型的下載另存為html。 嘗試使用其他瀏覽器,或者甚至更好地使用FTP客戶端來獲取文件,因此瀏覽器不是一個因素。
如果您想繼續使用瀏覽器,請嘗試執行以下操作,而不只是單擊鏈接:
將鼠標放在鏈接上,然后右鍵單擊。 如果您可以選擇“另存為”,則將文件另存為.csv。 如果選擇另存為,它將自動為您選擇.csv。
將內容/類型用作
header('Content-Type: application/csv');
而不是header('Content-Type: text/csv');
You can also use the below two lines
header("Content-type: text/x-csv");
header("Content-type: application/csv");
If you want to set any particular file name to the download file then you can add
header("Content-Disposition: attachment; filename=dates_for_".date('dMy').".csv");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.