【问题标题】:export and download as csv in php not working in chrome and IE but working in firefox在 php 中导出和下载为 csv 不能在 chrome 和 IE 中工作,但在 Firefox 中工作
【发布时间】:2014-05-23 23:03:04
【问题描述】:

我有一个简单的网页,它从数据库中提取一些数据并将其显示在 html 表中,并将数据存储在一些会话变量中。 我有一个“导出到 csv”按钮,它调用一个将结果导出到 csv 文件的页面。

ExportToCsv 文件的代码是:

<?php
    session_start(); 
    include "conn/sqlserverConn.php";

    function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
    }

    $data = $_SESSION['data'];
    $rows = $_SESSION['row'];
    $header = $_SESSION['header'];

    download_send_headers("data_export_" . date("Y-m-d") . ".csv");
    $file = fopen("php://output", 'w');
    fputcsv($file,$header);


    for($i=0; $i<$rows; ++$i)
    {


        $valuesArray=array();
        foreach($data[$i] as $name => $value)
        {
            $valuesArray[]=$value;
        }
        fputcsv($file,$valuesArray);
    }
    fclose($file);


    die();

?>

我的代码在 Firefox 中完美运行,但在 chrome 或 IE 中无法运行。在 chrome 和 IE 上显示错误 404(找不到对象!)。请告诉我是什么问题?

【问题讨论】:

  • 这个THREAD的可能重复
  • @ThinkDifferent 在您提到的线程中,代码在 chrome 中运行良好。如果是 IE,它无法识别它。在我的情况下,它也不能在 chrome 中工作并且给出 404 错误。 PS:-我尝试了该线程中给出的解决方案,但没有奏效。

标签: php internet-explorer google-chrome cross-browser export-to-csv


【解决方案1】:

正如博客文章中所述:http://www.exchangecore.com/blog/php-output-array-csv-headers/,我测试了以下内容,它在 IE8-11 和 chrome 版本 34 中运行。我认为它在其他浏览器中也可以正常运行。

要使用的标题:

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $fileName);    

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 2014-05-24
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多