Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and downloading CSV with PHP

I'm using PHP to create a CSV file from a database query. I run the query, set the headers, and load the page up in Firefox and the file promps for download and opens in excel just like it's supposed to. When I try it in IE, I get an error saying Internet Explorer cannot download ReportPrint.php from www.website.com.
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.

Not sure what can be done to fix this.

header('Content-Description: File Transfer');
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename=Report.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";
like image 336
AndyD273 Avatar asked Nov 05 '22 08:11

AndyD273


1 Answers

Internet Explorer tends to display these error messages when it's not able to cache the file and you appear to be trying to avoid caching. Try instead something like this:

<?php

$seconds = 30;

header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$seconds) . ' GMT');
header('Cache-Control: max-age=' . $seconds . ', s-maxage=' . $seconds . ', must-revalidate, proxy-revalidate');

session_cache_limiter(FALSE); // Disable session_start() caching headers
if( session_id() ){
    // Remove Pragma: no-cache generated by session_start()
    if( function_exists('header_remove') ){
        header_remove('Pragma');
    }else{
        header('Pragma:');
    }
}

?>

Adjust $seconds to your liking but don't set it to zero.

It also helps to use mod_rewrite to make IE believe that the download is a static file, e.g., http://example.com/Report.csv

Please report back and tell if it works for you.

like image 104
Álvaro González Avatar answered Nov 09 '22 03:11

Álvaro González