PHP中将网页导出为Word文档的代码


Posted in PHP onMay 25, 2012

一般,有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类中了。

/** 
* 根据HTML代码获取word文档内容 
* 创建一个本质为mht的文档,该函数会分析文件内容并从远程下载页面中的图片资源 
* 该函数依赖于类MhtFileMaker 
* 该函数会分析img标签,提取src的属性值。但是,src的属性值必须被引号包围,否则不能提取 
* 
* @param string $content HTML内容 
* @param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径,那么就需要填写这个参数,来让该函数自动填补成绝对路径。这个参数最后需要以/结束 
* @param bool $isEraseLink 是否去掉HTML内容中的链接 
*/ 
function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true ) 
{ 
$mht = new MhtFileMaker(); 
if ($isEraseLink) 
$content = preg_replace('/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i' , '$1' , $content); //去掉链接 
$images = array(); 
$files = array(); 
$matches = array(); 
//这个算法要求src后的属性值必须使用引号括起来 
if ( preg_match_all('/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i',$content ,$matches ) ) 
{ 
$arrPath = $matches[1]; 
for ( $i=0;$i<count($arrPath);$i++) 
{ 
$path = $arrPath[$i]; 
$imgPath = trim( $path ); 
if ( $imgPath != "" ) 
{ 
$files[] = $imgPath; 
if( substr($imgPath,0,7) == 'http://') 
{ 
//绝对链接,不加前缀 
} 
else 
{ 
$imgPath = $absolutePath.$imgPath; 
} 
$images[] = $imgPath; 
} 
} 
} 
$mht->AddContents("tmp.html",$mht->GetMimeType("tmp.html"),$content); 
for ( $i=0;$i<count($images);$i++) 
{ 
$image = $images[$i]; 
if ( @fopen($image , 'r') ) 
{ 
$imgcontent = @file_get_contents( $image ); 
if ( $content ) 
$mht->AddContents($files[$i],$mht->GetMimeType($image),$imgcontent); 
} 
else 
{ 
echo "file:".$image." not exist!<br />"; 
} 
} 
return $mht->GetFile(); 
}

使用方法:
$fileContent = getWordDocument($content,"http://www.yoursite.com/Music/etc/"); 
$fp = fopen("test.doc", 'w'); 
fwrite($fp, $fileContent); 
fclose($fp);

其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址
注意,在使用这个函数之前,您需要先包含类MhtFileMaker,这个类可以帮助我们生成Mht文档。
<?php 
/*********************************************************************** 
Class: Mht File Maker 
Version: 1.2 beta 
Date: 02/11/2007 
Author: Wudi <wudicgi@yahoo.de> 
Description: The class can make .mht file. 
***********************************************************************/ 
class MhtFileMaker{ 
var $config = array(); 
var $headers = array(); 
var $headers_exists = array(); 
var $files = array(); 
var $boundary; 
var $dir_base; 
var $page_first; 
function MhtFile($config = array()){ 
} 
function SetHeader($header){ 
$this->headers[] = $header; 
$key = strtolower(substr($header, 0, strpos($header, ':'))); 
$this->headers_exists[$key] = TRUE; 
} 
function SetFrom($from){ 
$this->SetHeader("From: $from"); 
} 
function SetSubject($subject){ 
$this->SetHeader("Subject: $subject"); 
} 
function SetDate($date = NULL, $istimestamp = FALSE){ 
if ($date == NULL) { 
$date = time(); 
} 
if ($istimestamp == TRUE) { 
$date = date('D, d M Y H:i:s O', $date); 
} 
$this->SetHeader("Date: $date"); 
} 
function SetBoundary($boundary = NULL){ 
if ($boundary == NULL) { 
$this->boundary = '--' . strtoupper(md5(mt_rand())) . '_MULTIPART_MIXED'; 
} else { 
$this->boundary = $boundary; 
} 
} 
function SetBaseDir($dir){ 
$this->dir_base = str_replace("\\", "/", realpath($dir)); 
} 
function SetFirstPage($filename){ 
$this->page_first = str_replace("\\", "/", realpath("{$this->dir_base}/$filename")); 
} 
function AutoAddFiles(){ 
if (!isset($this->page_first)) { 
exit ('Not set the first page.'); 
} 
$filepath = str_replace($this->dir_base, '', $this->page_first); 
$filepath = 'http://mhtfile' . $filepath; 
$this->AddFile($this->page_first, $filepath, NULL); 
$this->AddDir($this->dir_base); 
} 
function AddDir($dir){ 
$handle_dir = opendir($dir); 
while ($filename = readdir($handle_dir)) { 
if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) { 
if (is_dir("$dir/$filename")) { 
$this->AddDir("$dir/$filename"); 
} elseif (is_file("$dir/$filename")) { 
$filepath = str_replace($this->dir_base, '', "$dir/$filename"); 
$filepath = 'http://mhtfile' . $filepath; 
$this->AddFile("$dir/$filename", $filepath, NULL); 
} 
} 
} 
closedir($handle_dir); 
} 
function AddFile($filename, $filepath = NULL, $encoding = NULL){ 
if ($filepath == NULL) { 
$filepath = $filename; 
} 
$mimetype = $this->GetMimeType($filename); 
$filecont = file_get_contents($filename); 
$this->AddContents($filepath, $mimetype, $filecont, $encoding); 
} 
function AddContents($filepath, $mimetype, $filecont, $encoding = NULL){ 
if ($encoding == NULL) { 
$filecont = chunk_split(base64_encode($filecont), 76); 
$encoding = 'base64'; 
} 
$this->files[] = array('filepath' => $filepath, 
'mimetype' => $mimetype, 
'filecont' => $filecont, 
'encoding' => $encoding); 
} 
function CheckHeaders(){ 
if (!array_key_exists('date', $this->headers_exists)) { 
$this->SetDate(NULL, TRUE); 
} 
if ($this->boundary == NULL) { 
$this->SetBoundary(); 
} 
} 
function CheckFiles(){ 
if (count($this->files) == 0) { 
return FALSE; 
} else { 
return TRUE; 
} 
} 
function GetFile(){ 
$this->CheckHeaders(); 
if (!$this->CheckFiles()) { 
exit ('No file was added.'); 
} 
$contents = implode("\r\n", $this->headers); 
$contents .= "\r\n"; 
$contents .= "MIME-Version: 1.0\r\n"; 
$contents .= "Content-Type: multipart/related;\r\n"; 
$contents .= "\tboundary=\"{$this->boundary}\";\r\n"; 
$contents .= "\ttype=\"" . $this->files[0]['mimetype'] . "\"\r\n"; 
$contents .= "X-MimeOLE: Produced By Mht File Maker v1.0 beta\r\n"; 
$contents .= "\r\n"; 
$contents .= "This is a multi-part message in MIME format.\r\n"; 
$contents .= "\r\n"; 
foreach ($this->files as $file) { 
$contents .= "--{$this->boundary}\r\n"; 
$contents .= "Content-Type: $file[mimetype]\r\n"; 
$contents .= "Content-Transfer-Encoding: $file[encoding]\r\n"; 
$contents .= "Content-Location: $file[filepath]\r\n"; 
$contents .= "\r\n"; 
$contents .= $file['filecont']; 
$contents .= "\r\n"; 
} 
$contents .= "--{$this->boundary}--\r\n"; 
return $contents; 
} 
function MakeFile($filename){ 
$contents = $this->GetFile(); 
$fp = fopen($filename, 'w'); 
fwrite($fp, $contents); 
fclose($fp); 
} 
function GetMimeType($filename){ 
$pathinfo = pathinfo($filename); 
switch ($pathinfo['extension']) { 
case 'htm': $mimetype = 'text/html'; break; 
case 'html': $mimetype = 'text/html'; break; 
case 'txt': $mimetype = 'text/plain'; break; 
case 'cgi': $mimetype = 'text/plain'; break; 
case 'php': $mimetype = 'text/plain'; break; 
case 'css': $mimetype = 'text/css'; break; 
case 'jpg': $mimetype = 'image/jpeg'; break; 
case 'jpeg': $mimetype = 'image/jpeg'; break; 
case 'jpe': $mimetype = 'image/jpeg'; break; 
case 'gif': $mimetype = 'image/gif'; break; 
case 'png': $mimetype = 'image/png'; break; 
default: $mimetype = 'application/octet-stream'; break; 
} 
return $mimetype; 
} 
} 
?>
PHP 相关文章推荐
Linux下进行MYSQL编程时插入中文乱码的解决方案
Mar 15 PHP
php在页面中调用fckeditor编辑器的方法
Jun 10 PHP
php中常量DIRECTORY_SEPARATOR用法深入分析
Nov 14 PHP
php操作xml入门之xml标签的属性分析
Jan 23 PHP
php中smarty模板条件判断用法实例
Jun 11 PHP
php实现批量修改文件名称的方法
Jul 23 PHP
Centos 6.5系统下编译安装PHP 7.0.13的方法
Dec 19 PHP
PHP下 Mongodb 连接远程数据库的实例代码
Aug 30 PHP
PHP使用栈解决约瑟夫环问题算法示例
Aug 27 PHP
php图片合成方法(多张图片合成一张)
Nov 25 PHP
php+Ajax无刷新验证用户名操作实例详解
Mar 04 PHP
PHP设计模式(四)原型模式Prototype实例详解【创建型】
May 02 PHP
php在文件指定行中写入代码的方法
May 23 #PHP
php替换超长文本中的特殊字符的函数代码
May 22 #PHP
php提示undefined index的几种解决方法
May 21 #PHP
openflashchart 2.0 简单案例php版
May 21 #PHP
PHP中去掉字符串首尾空格的方法
May 19 #PHP
有关PHP中MVC的开发经验分享
May 17 #PHP
php的array_multisort()使用方法介绍
May 16 #PHP
You might like
PHP中调用ASP.NET的WebService的代码
2011/04/22 PHP
php创建sprite
2014/02/11 PHP
PHP网页游戏学习之Xnova(ogame)源码解读(十五)
2014/06/30 PHP
php中Session的生成机制、回收机制和存储机制探究
2014/08/19 PHP
PHP实现简单实用的验证码类
2015/07/29 PHP
学习php设计模式 php实现合成模式(composite)
2015/12/08 PHP
JS实现浏览器菜单命令
2006/09/05 Javascript
javascript addBookmark 加入收藏 多浏览器兼容
2009/08/15 Javascript
在网站上应该用的30个jQuery插件整理
2011/11/03 Javascript
解析dom中的children对象数组元素firstChild,lastChild的使用
2013/07/10 Javascript
JQUERY dialog的用法详细解析
2013/12/19 Javascript
js读写json文件实例代码
2014/10/21 Javascript
javascript 获取浏览器版本
2015/01/21 Javascript
IE7浏览器窗口大小改变事件执行多次bug及IE6/IE7/IE8下resize问题
2015/08/21 Javascript
总结js中的一些兼容性易错的问题
2017/12/18 Javascript
简单通过settimeout看javascript的运行机制
2019/05/10 Javascript
Vue中点击active并第一个默认选中功能的实现
2020/02/24 Javascript
[04:14]从西雅图到上海——玩家自制DOTA2主题歌曲应援TI9
2019/07/11 DOTA
[57:22]完美世界DOTA2联赛PWL S2 FTD vs PXG 第二场 11.27
2020/12/01 DOTA
[01:48:04]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Elephant BO3 第一场 2月7日
2021/03/11 DOTA
[01:03:41]DOTA2-DPC中国联赛 正赛 Dynasty vs XG BO3 第三场 2月2日
2021/03/11 DOTA
Python实现向QQ群成员自动发邮件的方法
2014/11/19 Python
python开发简易版在线音乐播放器
2017/03/03 Python
python 利用turtle库绘制笑脸和哭脸的例子
2019/11/23 Python
Python&amp;&amp;GDAL实现NDVI的计算方式
2020/01/09 Python
X/HTML5 和 XHTML2
2008/10/17 HTML / CSS
Chemist Warehouse中文网:澳洲连锁大药房
2021/02/05 全球购物
爱心倡议书范文
2014/05/12 职场文书
节水口号标语
2014/06/19 职场文书
2014年初中班主任工作总结
2014/11/08 职场文书
廉政承诺书
2015/01/19 职场文书
2015年新农村建设工作总结
2015/05/22 职场文书
vue3中的组件间通信
2021/03/31 Vue.js
mysql对于模糊查询like的一些汇总
2021/05/09 MySQL
解决redis批量删除key值的问题
2022/03/23 Redis
SQL Server 忘记密码以及重新添加新账号
2022/04/26 SQL Server