2

I have a simple web page which pulls some data from DB and displays it in a html table and stores the data in some session variables. I have a button "Export to csv" which calls a page which exports the results to a csv file.

The code for ExportToCsv file is:

<?php
    session_start(); 
    include "conn/sqlserverConn.php";

    function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
    }

    $data = $_SESSION['data'];
    $rows = $_SESSION['row'];
    $header = $_SESSION['header'];

    download_send_headers("data_export_" . date("Y-m-d") . ".csv");
    $file = fopen("php://output", 'w');
    fputcsv($file,$header);


    for($i=0; $i<$rows; ++$i)
    {


        $valuesArray=array();
        foreach($data[$i] as $name => $value)
        {
            $valuesArray[]=$value;
        }
        fputcsv($file,$valuesArray);
    }
    fclose($file);


    die();

?>

My code is working flawlessly in firefox but it is not working in chrome or IE. On chrome and IE it is showing error 404 (Object not found!). Please tell me what is the problem ?

shanal
  • 105
  • 3
  • 9
  • Possible duplicate of this [THREAD](http://stackoverflow.com/questions/2232103/how-do-i-get-csv-file-to-download-on-ie-works-on-firefox?rq=1) – Think Different Apr 10 '14 at 10:01
  • @ThinkDifferent In the thread you mentioned the code is working fine in chrome. and in case of IE it is failing to recognize it. In my case it is not working in chrome also and is giving 404 error. PS:- I tried the solution which was given in that thread but it did not work. – shanal Apr 10 '14 at 10:09

1 Answers1

1

As outlined in the blog article at: http://www.exchangecore.com/blog/php-output-array-csv-headers/, I tested the following and it worked in IE8-11, and in chrome version 34. I presume it will work in other browsers fine as well.

Headers to use:

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $fileName);    
Joe Meyer
  • 4,315
  • 20
  • 28