【问题标题】:Creating and downloading CSV with PHP使用 PHP 创建和下载 CSV
【发布时间】:2010-09-17 19:09:42
【问题描述】:

我正在使用 PHP 从数据库查询中创建 CSV 文件。 我运行查询,设置标题,并在 Firefox 中加载页面,文件提示下载并在 excel 中打开,就像它应该做的那样。 当我在 IE 中尝试时,我收到一条错误消息: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.

不知道可以做些什么来解决这个问题。

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

【问题讨论】:

  • 旁注:Expires 标头需要 date

标签: php http-headers


【解决方案1】:

当 Internet Explorer 无法缓存文件并且您似乎试图避免缓存时,它往往会显示这些错误消息。试试这样的:

<?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:');
    }
}

?>

根据您的喜好调整$seconds,但不要将其设置为零。

使用mod_rewrite也有助于让IE认为下载的是静态文件,例如http://example.com/Report.csv

请报告并告诉它是否适合您。

【讨论】:

  • 一旦我输入Pragma: Public,它就开始工作了。更改过期时间似乎没有任何区别......不知道
  • 如果我没记错的话,Pragma 的唯一有效值是no-cache。将其设置为其他任何值只会使浏览器忽略它(因为它不是已知值)并且与删除标题相同。无论如何,我很高兴它解决了您的问题。
  • 我遇到了同样的问题; Expires 标头没有任何效果,但只需清除 Cache-Control 和 Pragma 标头就可以了。 +1
【解决方案2】:

删除Pragma: no-cache 标头。此标头阻止 IE 下载文件。

【讨论】:

  • 好吧,这可能已经完成了...删除 no-cache 并没有解决它,但我发现另一个地方是我从我的站点下载 PDF 文件并注意到有几行我没有有。我认为是 header("Pragma: public") 解决了它。
  • 看来删除标题是您的实际解决方法。但是,仅仅停止添加它是不够的:如果您使用会话,PHP 可以自行添加它。
【解决方案3】:

检查 IE 的安全设置,可能是设置为不下载 CSV 文件。

【讨论】:

  • 我检查了设置并没有立即看到任何内容。然后我去了另一个网站,并能够下载动态创建的 CSV。最后,我创建了一个静态 CSV test.csv,它下载得很好,所以我很确定它与标题有关。
  • 另外,我的一位同事尝试在 Windows 7 的全新开箱即用版本上下载生成的 CSV,但也失败了。
【解决方案4】:

改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-22
    • 2011-06-29
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2013-04-21
    相关资源
    最近更新 更多