PHP操作Word文档的方法有很多,这里再为大家提供一种方法。
原理
一般,有2种方法可以导出doc文档,一种是使用com,并且作为php的一个扩展库安装到服务器上,然后创建一个com,调用它的方法。安装过office的服务器可以调用一个叫word.application的com,可以生成word文档,不过这种方式我不推荐,因为执行效率比较低(我测试了一下,在执行代码的时候,服务器会真的去打开一个word客户端)。理想的com应该是没有界面的,在后台进行数据转换,这样效果会比较好,但是这些扩展一般需要收费。
第2种方法,就是用PHP将我们的doc文档内容直接写入一个后缀为doc的文件中即可。使用这种方法不需要依赖第三方扩展,而且执行效率较高。
word本身的功能还是很强大的,它可以打开html格式的文件,并且能够保留格式,即使后缀为doc,它也能识别正常打开。这就为我们提供了方便。但是有一个问题,html格式的文件中的图片只有一个地址,真正的图片是保存在其他地方的,也就是说,如果将HTML格式写入doc中,那么doc中将不能包含图片。那我们如何创建包含图片的doc文档呢?我们可以使用和html很接近的mht格式。
mht格式和html很类似,只不过在mht格式中,外部链接进来的文件,比如图片、Javascript、CSS会被base64进行编码存储。因此,单个mht文件就可以保存一个网页中的所有资源,当然,相比html,它的尺寸也会比较大。
mht格式能被word识别吗?我将一个网页保存成mht,然后修改后缀名为doc,再用word打开,OK,word也可以识别mht文件,并且可以显示图片。
好了,既然doc可以识别mht,下面就是考虑如何将图片放入mht了。由于html代码中的图片的地址都是写在img标签的src属性中,因此,只要提取html代码中的src属性值,就可以获得图片地址。当然,有可能您获取到的是相对路径,没关系,加上URL的前缀,改成绝对路径就可以了。有了图片地址,我们就可以通过file_get_content函数获取到图片文件的具体内容,然后调用base64_encode函数将文件内容编码成base64编码,最后插入到mht文件的合适位置即可。
最后,我们有两种方法将文件发送给客户端,一种是先在服务器端生成一个doc文档,然后将这个doc文档的地址记录下来,最后,通过header("location:xx.doc");就可以让客户端下载这个doc。还有一种是直接发送html请求,修改HTML协议的header部分,将它的content-type设置为application/doc,将content-disposition设置为attachment,后面跟上文件名,发送完html协议以后,直接将文件内容发送给客户端,也可以让客户端下载到这个doc文档。
实现
通过以上的原理介绍,相信大家应该对实现的过程有个初步的了解了,下面我给出一个导出函数,这个函数可以将HTML代码导出成一个mht文档,参数有3个,其中后2个为可选参数
content:要转换的HTML代码
absolutePath: 如果HTML代码中的图片地址都是相对路径,那么这个参数就是HTML代码中缺少的绝对路径。
isEraseLink:是否去掉HTML代码中的超链接
返回值为mht的文件内容,您可以通过file_put_content将它保存成后缀名为doc的文件
这个函数的主要功能其实就是分析HTML代码中的所有图片地址,并且依次下载下来。获取到了图片的内容以后,调用MhtFileMaker类,将图片添加到mht文件中。具体的添加细节,封装在MhtFileMaker类中了。
03 |
* 创建一个本质为mht的文档,该函数会分析文件内容并从远程下载页面中的图片资源 |
05 |
* 该函数会分析img标签,提取src的属性值。但是,src的属性值必须被引号包围,否则不能提取 |
07 |
* @param string $content HTML内容 |
08 |
* @param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径,那么就需要填写这个参数,来让该函数自动填补成绝对路径。这个参数最后需要以/结束 |
09 |
* @param bool $isEraseLink 是否去掉HTML内容中的链接 |
12 |
function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true ) |
14 |
$mht = new MhtFileMaker(); |
16 |
$content = preg_replace( '/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i' , '$1' , $content ); //去掉链接 |
20 |
//这个算法要求src后的属性值必须使用引号括起来 |
21 |
if ( preg_match_all( '/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i' , $content , $matches ) ) |
23 |
$arrPath = $matches [1]; |
24 |
for ( $i =0; $i < count ( $arrPath ); $i ++) |
27 |
$imgPath = trim( $path ); |
31 |
if ( substr ( $imgPath ,0,7) == 'http://' ) |
37 |
$imgPath = $absolutePath . $imgPath ; |
43 |
$mht ->AddContents( "tmp.html" , $mht ->GetMimeType( "tmp.html" ), $content ); |
46 |
for ( $i =0; $i < count ( $images ); $i ++) |
49 |
if ( @ fopen ( $image , 'r' ) ) |
51 |
$imgcontent = @ file_get_contents ( $image ); |
53 |
$mht ->AddContents( $files [ $i ], $mht ->GetMimeType( $image ), $imgcontent ); |
57 |
echo "file:" . $image . " not exist!<br />" ; |
62 |
return $mht ->GetFile(); |
使用方法:
1 |
$fileContent = getWordDocument( $content , "http://www.jbxue.com/Music/etc/" ); |
2 |
$fp = fopen ( "test.doc" , 'w' ); |
3 |
fwrite( $fp , $fileContent ); |
其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址
注意,在使用这个函数之前,您需要先包含类MhtFileMaker,这个类可以帮助我们生成Mht文档。
002 |
/*********************************************************************** |
003 |
Class: Mht File Maker |
005 |
Author: Wudi <wudicgi@yahoo.de> |
006 |
Description: The class can make .mht file. |
007 |
***********************************************************************/ |
009 |
var $config = array (); |
010 |
var $headers = array (); |
011 |
var $headers_exists = array (); |
012 |
var $files = array (); |
016 |
function MhtFile( $config = array ()){ |
018 |
function SetHeader( $header ){ |
019 |
$this ->headers[] = $header ; |
020 |
$key = strtolower ( substr ( $header , 0, strpos ( $header , ':' ))); |
021 |
$this ->headers_exists[ $key ] = TRUE; |
023 |
function SetFrom( $from ){ |
024 |
$this ->SetHeader( "From: $from" ); |
026 |
function SetSubject( $subject ){ |
027 |
$this ->SetHeader( "Subject: $subject" ); |
029 |
function SetDate( $date = NULL, $istimestamp = FALSE){ |
033 |
if ( $istimestamp == TRUE) { |
034 |
$date = date ( 'D, d M Y H:i:s O' , $date ); |
036 |
$this ->SetHeader( "Date: $date" ); |
038 |
function SetBoundary( $boundary = NULL){ |
039 |
if ( $boundary == NULL) { |
040 |
$this ->boundary = '--' . strtoupper (md5(mt_rand())) . '_MULTIPART_MIXED' ; |
042 |
$this ->boundary = $boundary ; |
045 |
function SetBaseDir( $dir ){ |
046 |
$this ->dir_base = str_replace ( "\\" , "/" , realpath ( $dir )); |
048 |
function SetFirstPage( $filename ){ |
049 |
$this ->page_first = str_replace ( "\\" , "/" , realpath ( "{$this->dir_base}/$filename" )); |
051 |
function AutoAddFiles(){ |
052 |
if (!isset( $this ->page_first)) { |
053 |
exit ( 'Not set the first page.' ); |
055 |
$filepath = str_replace ( $this ->dir_base, '' , $this ->page_first); |
056 |
$filepath = 'http://mhtfile' . $filepath ; |
057 |
$this ->AddFile( $this ->page_first, $filepath , NULL); |
058 |
$this ->AddDir( $this ->dir_base); |
060 |
function AddDir( $dir ){ |
061 |
$handle_dir = opendir( $dir ); |
062 |
while ( $filename = readdir( $handle_dir )) { |
063 |
if (( $filename != '.' ) && ( $filename != '..' ) && ( "$dir/$filename" != $this ->page_first)) { |
064 |
if ( is_dir ( "$dir/$filename" )) { |
065 |
$this ->AddDir( "$dir/$filename" ); |
066 |
} elseif ( is_file ( "$dir/$filename" )) { |
067 |
$filepath = str_replace ( $this ->dir_base, '' , "$dir/$filename" ); |
068 |
$filepath = 'http://mhtfile' . $filepath ; |
069 |
$this ->AddFile( "$dir/$filename" , $filepath , NULL); |
073 |
closedir ( $handle_dir ); |
075 |
function AddFile( $filename , $filepath = NULL, $encoding = NULL){ |
076 |
if ( $filepath == NULL) { |
077 |
$filepath = $filename ; |
079 |
$mimetype = $this ->GetMimeType( $filename ); |
080 |
$filecont = file_get_contents ( $filename ); |
081 |
$this ->AddContents( $filepath , $mimetype , $filecont , $encoding ); |
083 |
function AddContents( $filepath , $mimetype , $filecont , $encoding = NULL){ |
084 |
if ( $encoding == NULL) { |
085 |
$filecont = chunk_split ( base64_encode ( $filecont ), 76); |
086 |
$encoding = 'base64' ; |
088 |
$this ->files[] = array ( 'filepath' => $filepath , |
089 |
'mimetype' => $mimetype , |
090 |
'filecont' => $filecont , |
091 |
'encoding' => $encoding ); |
093 |
function CheckHeaders(){ |
094 |
if (! array_key_exists ( 'date' , $this ->headers_exists)) { |
095 |
$this ->SetDate(NULL, TRUE); |
097 |
if ( $this ->boundary == NULL) { |
098 |
$this ->SetBoundary(); |
101 |
function CheckFiles(){ |
102 |
if ( count ( $this ->files) == 0) { |
109 |
$this ->CheckHeaders(); |
110 |
if (! $this ->CheckFiles()) { |
111 |
exit ( 'No file was added.' ); |
113 |
$contents = implode( "\r\n" , $this ->headers); |
115 |
$contents .= "MIME-Version: 1.0\r\n" ; |
116 |
$contents .= "Content-Type: multipart/related;\r\n" ; |
117 |
$contents .= "\tboundary=\"{$this->boundary}\";\r\n" ; |
118 |
$contents .= "\ttype=\"" . $this ->files[0][ 'mimetype' ] . "\"\r\n" ; |
119 |
$contents .= "X-MimeOLE: Produced By Mht File Maker v1.0 beta\r\n" ; |
121 |
$contents .= "This is a multi-part message in MIME format.\r\n" ; |
123 |
foreach ( $this ->files as $file ) { |
124 |
$contents .= "--{$this->boundary}\r\n" ; |
125 |
$contents .= "Content-Type: $file[mimetype]\r\n" ; |
126 |
$contents .= "Content-Transfer-Encoding: $file[encoding]\r\n" ; |
127 |
$contents .= "Content-Location: $file[filepath]\r\n" ; |
129 |
$contents .= $file [ 'filecont' ]; |
132 |
$contents .= "--{$this->boundary}--\r\n" ; |
135 |
function MakeFile( $filename ){ |
136 |
$contents = $this ->GetFile(); |
137 |
$fp = fopen ( $filename , 'w' ); |
138 |
fwrite( $fp , $contents ); |
141 |
function GetMimeType( $filename ){ |
142 |
$pathinfo = pathinfo ( $filename ); |
143 |
switch ( $pathinfo [ 'extension' ]) { |
144 |
case 'htm' : $mimetype = 'text/html' ; break ; |
145 |
case 'html' : $mimetype = 'text/html' ; break ; |
146 |
case 'txt' : $mimetype = 'text/plain' ; break ; |
147 |
case 'cgi' : $mimetype = 'text/plain' ; break ; |
148 |
case 'php' : $mimetype = 'text/plain' ; break ; |
149 |
case 'css' : $mimetype = 'text/css' ; break ; |
150 |
case 'jpg' : $mimetype = 'image/jpeg' ; break ; |
151 |
case 'jpeg' : $mimetype = 'image/jpeg' ; break ; |
152 |
case 'jpe' : $mimetype = 'image/jpeg' ; break ; |
153 |
case 'gif' : $mimetype = 'image/gif' ; break ; |
154 |
case 'png' : $mimetype = 'image/png' ; break ; |
155 |
default : $mimetype = 'application/octet-stream' ; break ; |
上面讨论了通过mht文件,来实现PHP导出doc格式的。这种方法可以解决一个难题,就是使导出的doc文件中包含图片,当然,如果您要包含更多的内容,比如CSS样式表,只需要用正则表达式分析HTML代码中的link标签,提取css样式文件的地址,然后读取并编码成base64,最后加入到mht文件中就可以了。
- PHP网页导出Word文档的方法分离
今天要探讨的是PHP网页导出Word文档的方法,使用其他语言的朋友也可以参考,因为原理是差不多的. 原理 一般,有2种方法可以导出doc文档,一种是使用com,并且作为php的一个扩展库安装到服务器上 ...
- .NET通过调用Office组件导出Word文档
.NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...
- C# 导出word文档及批量导出word文档(1)
这里用到了两个dll,一个是aspose.word.dll,另外一个是ICSharpCode.SharpZipLib.dll,ICSharpCode.SharpZipLib.dll是用于批量 ...
- C# 导出word文档及批量导出word文档(4)
接下来是批量导出word文档和批量打印word文件,批量导出word文档和批量打印word文件的思路差不多,只是批量打印不用打包压缩文件,而是把所有文件合成一个word,然后通过js来调用 ...
- C#导出Word文档开源组件DocX
1.帮助文档,这东西找了很久,而且它版本很旧,还是英文,W8.1系统上打不开 http://download.csdn.net/detail/zuofangyouyuan/7673573 2.开源网址 ...
- freemarker导出word文档——WordXML格式解析
前不久,公司一个项目需要实现导出文档的功能,之前是一个同事在做,做了3个星期,终于完成了,但是在项目上线之后却发现导出的文档有问题,此时,这个同事已经离职,我自然成为接班者,要把导出功能实现,但是我看 ...
- 自动生成并导出word文档
今天很荣幸又破解一现实难题:自动生成并导出word文档 先看页面效果: word效果: 代码: 先搭建struts2项目 创建action,并在struts.xml完成注册 <?xml vers ...
- Java 用Freemarker完美导出word文档(带图片)
Java 用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...
- freemarker导出word文档
使用freemarker导出word文档的过程 **************************************************************************** ...
随机推荐
- ios中UIButton选中状态切换
关于UIButton的事件枚举有许多,平时用的少所以很多的都不是很清楚,今天了解了下,看了以前的代码,觉得在UIButton选中时操作写了许多冗余代码,而忽略了UIButton一个很重要的属性,如下: ...
- Java基础 Day14 泛型
//为什么要使用泛型 //1.解决元素存储的安全性的问题 //2.解决获取元素时,须要类型转换的问题 //未使用泛型 package org.tizen.test; import java.util. ...
- WebService 设计总结
接触过非常多电商的WebService,有种一看就蛋疼的设计,今天要从这个反例说一说 WebService 的设计. [WebMethod] public string QueryOrderDetai ...
- Upgrading to MySQL 5.7---focusing on temporal types
https://www.percona.com/blog/2016/04/27/upgrading-to-mysql-5-7-focusing-on-temporal-types/ http://ww ...
- 文件I/O(不带缓冲)之open函数
调用open函数可以打开或创建一个文件. #include <fcntl.h> int open( const char *pathname, int oflag, ... /* mode ...
- Android(java)学习笔记154:使用GridView以及重写BaseAdapter
1.BaseAdapter: 对于ListView.GridView.Gallery.Spinner等等,它是它们的适配器,直接继承自接口类Adapter的,使用BaseAdapter时需要重写很多方 ...
- Windows系统下用命令行编译C/C++程序过程总结
转自:http://www.cnblogs.com/caikehe/archive/2013/01/12/2858017.html (1)先用记事本编写如下所示的代码,并另存为hello.cpp,假设 ...
- FastDFS配置过程
在我的生产环境中利用FastDFS实现动静分离的方案
- hdu 1040 As Easy As A+B
As Easy As A+B Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) T ...
- VIM 选择多行,复制粘贴
进入VIM,比如编辑一个文件, 1.进行选择,是V模式,按V键,进入该模式,然后选择要复制的行 2. 选择好之后,再按y键,即使复制到了 3.然后光标进入要复制的行之后,按一下P键,就粘贴了,oh y ...