【发布时间】:2011-04-11 21:15:42
【问题描述】:
我有一个 PHP 文件,它使用位于 http://pear.php.net/package/Spreadsheet_Excel_Writer/ 的模块生成 xls 文件
我可以很好地创建示例文档,当我打开它时,它看起来很好。
我的下一步是把它变成一个可下载的链接。为此,我这样做了:
$mimeType = "application/vnd.ms-excel";
$file_name = "test.xls";
$file_path = "/tmp/".$file_name;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Type: application/' . $mimeType);
header('Content-Length: '.$size);
header("Content-Disposition: attachment;filename=$file_name ");
header("Content-Transfer-Encoding: binary ");
// open the file in binary read-only mode
// display the error messages if the file can´t be opened
$file = & fopen($file_path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
但是,当我下载该文件时,它在 Excel 和 OpenOffice 中都包含大量垃圾数据。差异表示 /tmp 文件夹中的二进制文件和下载的文件彼此不同。我猜它与标头或 fpassthru 有关,但我在调试问题时运气不佳。
对问题所在有什么想法吗?
【问题讨论】:
-
如果您只是读取文件内容并将其传送到浏览器,我会使用 file_get_contents() 而不是 fpassthru。
-
readfile()更好,因为它会流式传输文件,而不是将整个内容吞入内存。您可以使用 file_get_contents 轻松超过 PHP memory_limit -
你得到解决方案了吗?