PHP 代码:php 程序中将网页生成 word 文档并提供下载的代码
在这篇文章中主要解决两个问题:
1:在 php 中如何把 html 中的内容生成到 word
文档中
2:php 把 html 中的内容生成到 word 文档中时,不居中显示问题,即会默认按照 web 视
图进行显示。
3:php 把 html 中的内容生成到 word
文档中时,相关样式不兼容问题
正文:
代码如下:
echo
'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-
microsoft-com:office:word" xmlns="
http://www.w3.org/TR/REC-html40
">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<xml><w:WordDocument><w:View>
</w:View></xml>
<script src="includes/js/ztree/js/jquery-1.4.4.min.js" type="text/javascript"></script>
</head>';
echo
'<body><table
class
="table_dayin">
<caption
class
="table_caption">';
echo
"数字化教学系统电子备课稿<br>
<span>
学科 <em style="border-bottom: 1px solid #545454;">语文</em>
学校 <em
style="border-bottom: 1px solid #545454;">实验中学</em></span>
</caption>";
echo
'</table></body></html>';
ob_start();
//
打开缓冲区
header("Cache-Control: public");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
if
(
strpos
(
$_SERVER
["HTTP_USER_AGENT"],'MSIE')) {
header('Content-Disposition: attachment; filename=test.doc');
}
else
if
(
strpos
(
$_SERVER
["HTTP_USER_AGENT"],'Firefox')) {
Header('Content-Disposition: attachment; filename=test.doc');
}
else
{
header('Content-Disposition: attachment; filename=test.doc');
}
header("Pragma:no-cache");
header("Expires:0");
ob_end_flush();
//
输出全部内容到浏览器
注:以上代码部分提供了在 php 程序文件中生成内容到 word
文档中并提供下载功能。
针对第 2 个问题,下载到本地的 word 文档打开后显示默认按照 web 视图进行显示的问题:
如下图: