简体   繁体   中英

download csv file with php

I have a file csv with code:

// put data to file
    $file = 'file.csv';
        $fp = fopen($file, 'w');
        foreach ($excel as $fields) {               
            fputcsv($fp, $fields);
        }

// download file when click button:

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

Data in file.csv (file.csv in publuc folder):

[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]

But when i click button to download file, data in file dowloaded is all html of page:

<!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..

How to fix it? Thanks very much!

a bit late but I think everyone missed the phalcon tag. what is missing is the

$this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);

Here is my way to handle this.

$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 - For me it is a string made from array but you can also use file_get_contents()

I would need more information to answer with certainty, but it sounds like the browser is simply configured to save this type of download as html. Try using another browser or even better use an FTP client to get the file so the browser is not a factor.

If you would like to continue to use the browser, try doing the following instead of just clicking the link:

Put the mouse over the link and then right click. If you have an option to "save as" save the file as a .csv. It may automatically select .csv for you if you choose save as.

use content/Type as,

header('Content-Type: application/csv');

instead of 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM