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 Interne开发者_如何转开发t 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.
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";
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.
Remove the Pragma: no-cache
header. This header prevents IE from downloading the file.
Check the security settings of IE, may be it's configured not to download CSV files.
Change
header("Content-Disposition: attachment; filename=Report.csv");
to
header("Content-Disposition: attachment;filename=Report.csv");
精彩评论