代码之家  ›  专栏  ›  技术社区  ›  AndyD273

用PHP创建和下载csv

  •  5
  • AndyD273  · 技术社区  · 14 年前

    我正在使用PHP从数据库查询中创建一个csv文件。 我运行查询,设置头文件,并在firefox和promps文件中加载页面以供下载,然后像预期的那样在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";
    
    4 回复  |  直到 14 年前
        1
  •  1
  •   jmz    14 年前

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

        2
  •  3
  •   Álvaro González    14 年前

    当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

    请反馈并告知是否适合您。

        3
  •  0
  •   rubayeet    14 年前

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

        4
  •  -2
  •   Theodore R. Smith    14 年前

    变化

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

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