PHP:发送WORD文档文件下载

标签 php file ms-word download content-disposition

这个问题很简单,有很多答案,全部相同或几乎相同,但对于我的情况,它没有按预期解决? 目标:使用 PHP 发送 WORD 文件作为附件(简单...) 意思是:这是代码:

// send the file to the browser
header("Cache-Control: no-store");
header("Content-Type: application/octet-stream");
//header("Content-type: application/msword");
header('Content-Disposition: attachment; filename="'. basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. filesize($filename));
ob_clean();
flush();
readfile($filename);
exit();

好吧,一切似乎都正确,但我保存在计算机上的文件无法被 MS-WORD 读取:它读取一些特殊字符,如:

PK ! /Œt1« á [Content_Types].xml ...

但是如果我从服务器打开原件,一切正常。 我错过了一些明显的东西...... 欢迎任何建议,因为我几乎尝试了所有阅读的方法...但结果仍然相同。

最佳答案

也许您的输出文件 header 有误。我的脚本中有类似这样的东西,我用它来下载文件:

$tmp = explode(".",$file['filename']);
switch ($tmp[count($tmp)-1]) {
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "docx":
  case "doc": $ctype="application/msword"; break;
  case "csv":
  case "xls":
  case "xlsx": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  case "tif":
  case "tiff": $ctype="image/tiff"; break;
  case "psd": $ctype="image/psd"; break;
  case "bmp": $ctype="image/bmp"; break;
  case "ico": $ctype="image/vnd.microsoft.icon"; break;
  default: $ctype="application/force-download";
}

header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".$filename."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( 'files/'.$file['filename'] );

我从数据库中获取的文件名。

关于PHP:发送WORD文档文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11518576/

相关文章:

PHP - 格式化 HH :MM:SS to 12hr HH:MM:a string

Java:如何从文件的每一行读取 4 个数字。并将它们放入变量中?

ruby-on-rails - 使用 RubyZip 生成文件并下载为 zip

php - 使用带有 ftp 服务器的 postgresql 的复制功能

php mysql更新限制

java - 将整数存储在数组中后打印文件中的整数数量?

c# - Word Document.Close 和线程中止异常 Windows 7

vba - 在 MS Word 中打印字体的所有字形

c# - C# 中的 Word 自动化语法

php - 使用 GridView 在 Yii2.0 中显示过滤器的空白行