【问题标题】:CSV Export Script only generates error in IE?CSV 导出脚本只在 IE 中生成错误?
【发布时间】:2010-07-06 15:23:03
【问题描述】:

我有一个 CSV 导出脚本 (enrdata_arch.php),它从现有数据库中调用信息并将其导出为 CSV 格式。但是由于某种原因,该脚本仅在 Internet Explorer 中返回以下错误:

Microsoft Office Excel 无法访问文件“https://www.domain.com/admin/enrdata_arch.php”。有几个可能的原因:

  • 文件名或路径不存在
  • 该文件正被另一个程序使用
  • 您尝试保存的工作簿与当前打开的工作簿同名

**

原脚本贴在下面:

**

<?php

$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'db_name';
$table = 'table_name';
$archive = 'archive_name';
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect.".mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= '"'.$rowr[$j].'",'; 
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;

//transfers old data to archive
$transfer = mysql_query('INSERT INTO '.$archive.' SELECT * FROM '.$table) or die(mysql_error());

//empties existing table
$query = mysql_query('TRUNCATE TABLE '.$table) or die(mysql_error());

mysql_close($link);
exit;
?>

似乎脚本仅在使用 IE 时才尝试保存和打开 PHP 文件。有什么想法吗?

【问题讨论】:

    标签: php mysql csv export


    【解决方案1】:

    SSL 的标题是 IE 的一个已知问题

    我用

    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    

    'Pragma: public 是 IE/ssl 的关键

    CSV 文件的内容类型是

    text/csv
    

    或

    text/plain
    

    而不是

    application/vnd.ms-excel
    

    特别是 MS Excel .xls speardsheets

    【讨论】:

    • 感谢您的帮助。你介意解释一下你的标题添加吗?过期日期/最后修改日期的总体用途是什么?
    • 那些日期标头是缓存标头。如果浏览器之前已经向服务器发送了类似的请求,那么它可能不会再次发送请求,因为它认为它已经在缓存中拥有该文件。这些标头确保浏览器不会缓存请求,因此它将始终从服务器发出请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多