PHP下载excel文件已损坏


PHP downloading excel file becomes corrupt

我有一个excel文件,希望用户能够从我的服务器下载。我在这里看了很多问题,但我找不到正确下载文件的方法,没有损坏。我想是头球,但我还没有一个有效的组合。这就是我现在所拥有的,在我收到的损坏文件中,我可以看到我想要的电子表格的列名,但它都搞砸了。

$filename = '/var/www/web1/web/public/temporary/Spreadsheet.xls';        
header("Content-type: application/octet-stream");
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=ExcelFile.xls;");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);

edit:解决方案我忘记添加我正在使用Zend,并且它在尝试使用本机php方法时损坏了文件。我的最终代码是在我的控制器中放置一个指向另一个操作的链接,并从那里下载文件

public function downloadAction(){
        $file = '/var/www/web1/web/public/temporary/Spreadsheet.xls';
        header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="Spreadsheet.xls"');
    readfile($file);
    // disable the view ... and perhaps the layout
    $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

    }

试着这样做

 ob_get_clean();
 echo file_get_contents($filename);
 ob_end_flush();

对于一个,只指定Content-Type一次。你可以使用excel特定的标题,但通用的application/octet-stream可能是一个更安全的选择,只是为了让它工作(真正的区别是浏览器向用户显示的"你想用什么打开这个文件",但基本浏览器也可以依赖扩展名)

此外,请确保指定Content-Length并转储要输出的文件的大小(以字节为单位)。浏览器需要知道文件有多大,以及它希望接收的内容有多少(这样它就不会中途停止,或者打嗝不会中断文件下载)。

因此,整个文件应该包括:

<?php
  $filename = '/var/www/web1/web/public/temporary/Spreadsheet.xls';
  header("Content-Disposition: attachment; filename=ExcelFile.xls;");
  header('Content-Type: application/octet-stream');
  header('Content-Length: ' . filesize($filename));
  header("Pragma: no-cache");
  header("Expires: 0");
  @readfile($filename);
$file_name = "file.xlsx";
// first, get MIME information from the file
$finfo = finfo_open(FILEINFO_MIME_TYPE); 
$mime =  finfo_file($finfo, $file_name);
finfo_close($finfo);
// send header information to browser
header('Content-Type: '.$mime);
header('Content-Disposition: attachment;  filename="download_file_name.xlsx"');
header('Content-Length: ' . filesize($file_name));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
//stream file
ob_get_clean();
echo file_get_contents($file_name);
ob_end_flush();