Creating and downloading CSV with PHP

你离开我真会死。 提交于 2020-01-03 13:58:28

问题


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";

回答1:


Remove the Pragma: no-cache header. This header prevents IE from downloading the file.




回答2:


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.




回答3:


Check the security settings of IE, may be it's configured not to download CSV files.




回答4:


Change

header("Content-Disposition: attachment; filename=Report.csv");

to

header("Content-Disposition: attachment;filename=Report.csv");


来源:https://stackoverflow.com/questions/3738221/creating-and-downloading-csv-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!