我有一个简单的网页,它从数据库中提取一些数据并将其显示在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(找不到对象!)。请告诉我这是什么问题?
答案 0 :(得分: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);