Safari在下载时添加了".html"后缀

14

我有一个小函数,它使用PHPexcel创建.xls文档,然后将其发送到php://output。然后用户下载它。
除了mac os x上的safari出于某种原因添加了.html扩展名之外,一切都正常。
所以结果文件命名为report.xls.html。内容是正确的,但对用户来说很烦人。

我该如何解决这个问题?

以下是我的代码的一部分:

$filename = 'report.xls';

header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$filename.'"'); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save('php://output');
6个回答

34

我遇到了同样的问题

在脚本结尾处加入 exit; 就解决了

$filename = 'report.xls';
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$filename.'"'); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save('php://output');
exit;

5
感谢上帝,这个解决方案有效,但我可以问一下为什么 exit; 可以解决问题吗? - cytsunny
1
有人知道为什么exit()可以解决这个问题吗? - Miguel Stevens

1

我有一个类似的问题,我用退出函数解决了它(使用参数状态)。

在模型中:

public static function xls($id)
{
    $xls = new PHPExcel();
    //Code ...
    $objWriter = new \PHPExcel_Writer_Excel5($xls);

    ob_start();
    $objWriter->save('php://output');
    $excelOutput = ob_get_clean();

    return $excelOutput;
}

在控制器中:

public function xls($id)
{
    header('Expires: Mon, 1 Apr 1974 05:00:00 GMT');
    header('Last-Modified: ' . gmdate('D,d M YH:i:s') . ' GMT');
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: no-cache');
    header('Content-type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename=' . $id . '.xls');

    return exit(Controller::xls($id)); // <-- 
}

你知道为什么exit()可以解决这个问题吗? - Miguel Stevens

1

你可以使用JavaScript的window.location.href = "http://stackoverflow.com/file.xls"来打开xls文件。 - sourabh kasliwal
它有点能用。不是很优雅,但是如果我先保存文件,然后将浏览器指向它 - 它会被保存为 .xls。你能把它发布为答案,这样我就可以接受它了吗? - Davinel

0
如果有人仍然面临上述问题,请将内容类型更改为
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

0

对于遇到这个问题的任何人来说,这是浏览器自己的问题。使用JavaScript对我有用,但您需要添加HTML,然后使用JavaScript输出到浏览器。

<!doctype html>
<html>
     <head> <meta charset="UTF-8"> <title>Untitled  ocument</title> </head> 
     <body> 
          <script> window.location.href = http://example/file.docx"; </script> 
     </body>
</html>

0
你可以使用JavaScript代码
<script>
 window.location.href = "stackoverflow.com/file.xls";
</script>

这将打开那个xls源文件并可供下载。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接