如何使用 PHP 或 HTML 在浏览器中查看/打开 Word 文档

2021-12-31 00:00:00 file ms-word php html

如何在浏览器中打开和查看 .doc 文件扩展名?该文件位于我的服务器上.

How can I open and view a .doc file extension in my browser? The file is located on my server.

推荐答案

两个选项:第一个是链接到它,例如<a href="MyWordDocument.doc">My Word Document</a>,二是使用iframe,指向文档.然而,为了使其工作,大多数浏览器要求服务器随文档发送一个 Content-disposition: inline 标头.如果您无法配置您的网络服务器来执行此操作,您可以将文档包装在一些 php 中:

Two options: First is to just link to it, e.g. <a href="MyWordDocument.doc">My Word Document</a>, the second is to use an iframe and point it to the document. For this to work, however, most browsers require that the server sends a Content-disposition: inline header with the document. If you cannot configure your web server to do this, you can wrap the document in a bit of php:

<?php
header('Content-disposition: inline');
header('Content-type: application/msword'); // not sure if this is the correct MIME type
readfile('MyWordDocument.doc');
exit;

然后链接到该脚本而不是您的 Word 文档.

And then link to that script instead of your word document.

但这并不能保证有效;content-disposition 标头只是一个提示,任何浏览器都可以选择将其视为附件.

This isn't guaranteed to work though; the content-disposition header is just a hint, and any browser may choose to treat it as an attachment anyway.

另外,请注意 .doc 并不是完全可移植的;基本上,您需要 Word 才能正确显示它(Open Office 和其他一些开源应用程序做得不错,但还没有完全实现),并且浏览器必须支持将 Word 作为插件打开.

Also, note that .doc isn't exactly portable; basically, you need Word to display it properly (Open Office and a few other Open Source applications do kind of a decent job, but they're not quite there yet), and the browser must support opening Word as a plugin.

如果 .doc 文件格式要求不是一成不变的,那么 PDF 将是更好的选择(转换通常就像在 PDF 打印机上打印一样简单,比如从 Word 内部的CutePDF),或者也许你甚至可以将文档转换为 HTML(尽管里程可能会有所不同).

If the .doc file format requirement isn't set in stone, PDF would be a better choice (the conversion is usually as simple as printing it on a PDF printer, say, CutePDF, from inside Word), or maybe you can even convert the document to HTML (mileage may vary though).

相关文章