简体   繁体   中英

PHP 5.3 Download CSV

When a user clicks a button it's going to download a csv file. It works in IE9 and Chrome, but not Firefox. In Firefox 20, the content-type is not being set so it's downloading as a Firefox HTML Document.

       $filename = 'exportedLogs.csv';

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=" .$filename);
        header("Expires: 0");
        header("Pragma: public");

        $csv_file = fopen('php://output', 'w');

        $header_row = array('id', 'project', 'customer', 'time spent');

        fputcsv($csv_file, $header_row);
        foreach ($logs as $log) {
            $log = array(
                $log['Log']['id'],
                $log['Log']['project_id'],
                $log['Log']['customer_id'],
                $log['Log']['time_spent']
            );
            fputcsv($csv_file, $log);
        }
        fclose($csv_file);

I found out that the reason the header wasn't changing was because of cakePhp. For anybody else having this issue, you must do two things:

  1. Add 'csv' to Router::parseExtensions('csv');
  2. Add a '.csv' to the action in the form

@ThaJeztah provided a link that may be helpful to others. It's for json/xml, but the principals can be used for csv too.

http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#json-and-xml-views

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