原理
一般,有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類中了。
01 |
/** |
02 |
* 根據HTML代碼獲取word文檔內容 |
03 |
* 創建一個本質為mht的文檔,該函數會分析文件內容並從遠程下載頁面中的圖片資源 |
04 |
* 該函數依賴於類MhtFileMaker |
05 |
* 該函數會分析img標簽,提取src的屬性值。但是,src的屬性值必須被引號包圍,否則不能提取 |
06 |
* |
07 |
* @param string $content HTML內容 |
08 |
* @param string $absolutePath 網頁的絕對路徑。如果HTML內容里的圖片路徑為相對路徑,那么就需要填寫這個參數,來讓該函數自動填補成絕對路徑。這個參數最后需要以/結束 |
09 |
* @param bool $isEraseLink 是否去掉HTML內容中的鏈接 |
10 |
* by www.jbxue.com |
11 |
*/ |
12 |
function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true ) |
13 |
{ |
14 |
$mht = new MhtFileMaker(); |
15 |
if ( $isEraseLink ) |
16 |
$content = preg_replace( '/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i' , '$1' , $content ); //去掉鏈接 |
17 |
$images = array (); |
18 |
$files = array (); |
19 |
$matches = array (); |
20 |
//這個算法要求src后的屬性值必須使用引號括起來 |
21 |
if ( preg_match_all( '/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i' , $content , $matches ) ) |
22 |
{ |
23 |
$arrPath = $matches [1]; |
24 |
for ( $i =0; $i < count ( $arrPath ); $i ++) |
25 |
{ |
26 |
$path = $arrPath [ $i ]; |
27 |
$imgPath = trim( $path ); |
28 |
if ( $imgPath != "" ) |
29 |
{ |
30 |
$files [] = $imgPath ; |
31 |
if ( substr ( $imgPath ,0,7) == 'http://' ) |
32 |
{ |
33 |
//絕對鏈接,不加前綴 |
34 |
} |
35 |
else |
36 |
{ |
37 |
$imgPath = $absolutePath . $imgPath ; |
38 |
} |
39 |
$images [] = $imgPath ; |
40 |
} |
41 |
} |
42 |
} |
43 |
$mht ->AddContents( "tmp.html" , $mht ->GetMimeType( "tmp.html" ), $content ); |
44 |
45 |
46 |
for ( $i =0; $i < count ( $images ); $i ++) |
47 |
{ |
48 |
$image = $images [ $i ]; |
49 |
if ( @ fopen ( $image , 'r' ) ) |
50 |
{ |
51 |
$imgcontent = @ file_get_contents ( $image ); |
52 |
if ( $content ) |
53 |
$mht ->AddContents( $files [ $i ], $mht ->GetMimeType( $image ), $imgcontent ); |
54 |
} |
55 |
else |
56 |
{ |
57 |
echo "file:" . $image . " not exist!<br />" ; |
58 |
} |
59 |
} |
60 |
61 |
62 |
return $mht ->GetFile(); |
63 |
} |
1 |
$fileContent = getWordDocument( $content , "http://www.jbxue.com/Music/etc/" ); |
2 |
$fp = fopen ( "test.doc" , 'w' ); |
3 |
fwrite( $fp , $fileContent ); |
4 |
fclose( $fp ); |
注意,在使用這個函數之前,您需要先包含類MhtFileMaker,這個類可以幫助我們生成Mht文檔。
001 |
<?php |
002 |
/*********************************************************************** |
003 |
Class: Mht File Maker |
004 |
Version: 1.2 beta |
005 |
Author: Wudi <wudicgi@yahoo.de> |
006 |
Description: The class can make .mht file. |
007 |
***********************************************************************/ |
008 |
class MhtFileMaker{ |
009 |
var $config = array (); |
010 |
var $headers = array (); |
011 |
var $headers_exists = array (); |
012 |
var $files = array (); |
013 |
var $boundary ; |
014 |
var $dir_base ; |
015 |
var $page_first ; |
016 |
function MhtFile( $config = array ()){ |
017 |
} |
018 |
function SetHeader( $header ){ |
019 |
$this ->headers[] = $header ; |
020 |
$key = strtolower ( substr ( $header , 0, strpos ( $header , ':' ))); |
021 |
$this ->headers_exists[ $key ] = TRUE; |
022 |
} |
023 |
function SetFrom( $from ){ |
024 |
$this ->SetHeader( "From: $from" ); |
025 |
} |
026 |
function SetSubject( $subject ){ |
027 |
$this ->SetHeader( "Subject: $subject" ); |
028 |
} |
029 |
function SetDate( $date = NULL, $istimestamp = FALSE){ |
030 |
if ( $date == NULL) { |
031 |
$date = time(); |
032 |
} |
033 |
if ( $istimestamp == TRUE) { |
034 |
$date = date ( 'D, d M Y H:i:s O' , $date ); |
035 |
} |
036 |
$this ->SetHeader( "Date: $date" ); |
037 |
} |
038 |
function SetBoundary( $boundary = NULL){ |
039 |
if ( $boundary == NULL) { |
040 |
$this ->boundary = '--' . strtoupper (md5(mt_rand())) . '_MULTIPART_MIXED' ; |
041 |
} else { |
042 |
$this ->boundary = $boundary ; |
043 |
} |
044 |
} |
045 |
function SetBaseDir( $dir ){ |
046 |
$this ->dir_base = str_replace ( "\\" , "/" , realpath ( $dir )); |
047 |
} |
048 |
function SetFirstPage( $filename ){ |
049 |
$this ->page_first = str_replace ( "\\" , "/" , realpath ( "{$this->dir_base}/$filename" )); |
050 |
} |
051 |
function AutoAddFiles(){ |
052 |
if (!isset( $this ->page_first)) { |
053 |
exit ( 'Not set the first page.' ); |
054 |
} |
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); |
059 |
} |
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); |
070 |
} |
071 |
} |
072 |
} |
073 |
closedir ( $handle_dir ); |
074 |
} |
075 |
function AddFile( $filename , $filepath = NULL, $encoding = NULL){ |
076 |
if ( $filepath == NULL) { |
077 |
$filepath = $filename ; |
078 |
} |
079 |
$mimetype = $this ->GetMimeType( $filename ); |
080 |
$filecont = file_get_contents ( $filename ); |
081 |
$this ->AddContents( $filepath , $mimetype , $filecont , $encoding ); |
082 |
} |
083 |
function AddContents( $filepath , $mimetype , $filecont , $encoding = NULL){ |
084 |
if ( $encoding == NULL) { |
085 |
$filecont = chunk_split ( base64_encode ( $filecont ), 76); |
086 |
$encoding = 'base64' ; |
087 |
} |
088 |
$this ->files[] = array ( 'filepath' => $filepath , |
089 |
'mimetype' => $mimetype , |
090 |
'filecont' => $filecont , |
091 |
'encoding' => $encoding ); |
092 |
} |
093 |
function CheckHeaders(){ |
094 |
if (! array_key_exists ( 'date' , $this ->headers_exists)) { |
095 |
$this ->SetDate(NULL, TRUE); |
096 |
} |
097 |
if ( $this ->boundary == NULL) { |
098 |
$this ->SetBoundary(); |
099 |
} |
100 |
} |
101 |
function CheckFiles(){ |
102 |
if ( count ( $this ->files) == 0) { |
103 |
return FALSE; |
104 |
} else { |
105 |
return TRUE; |
106 |
} |
107 |
} |
108 |
function GetFile(){ |
109 |
$this ->CheckHeaders(); |
110 |
if (! $this ->CheckFiles()) { |
111 |
exit ( 'No file was added.' ); |
112 |
} //www.jb51.net |
113 |
$contents = implode( "\r\n" , $this ->headers); |
114 |
$contents .= "\r\n" ; |
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" ; |
120 |
$contents .= "\r\n" ; |
121 |
$contents .= "This is a multi-part message in MIME format.\r\n" ; |
122 |
$contents .= "\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" ; |
128 |
$contents .= "\r\n" ; |
129 |
$contents .= $file [ 'filecont' ]; |
130 |
$contents .= "\r\n" ; |
131 |
} |
132 |
$contents .= "--{$this->boundary}--\r\n" ; |
133 |
return $contents ; |
134 |
} |
135 |
function MakeFile( $filename ){ |
136 |
$contents = $this ->GetFile(); |
137 |
$fp = fopen ( $filename , 'w' ); |
138 |
fwrite( $fp , $contents ); |
139 |
fclose( $fp ); |
140 |
} |
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 ; |
156 |
} |
157 |
return $mimetype ; |
158 |
} |
159 |
} |
160 |
?> |