生成Word文檔是通過使用PHP中的庫或擴(kuò)展來操作。在PHP中,有許多第三方庫和擴(kuò)展可用于生成Word文檔,下面將介紹使用php生成word文檔的多種方法總有一種適合你。
1、使用 PHPWord庫生成word文檔
最常用的是PHPWord庫。
PHPWord - 用于讀寫文字處理文檔(OOXML、ODF、RTF、HTML、PDF)的純 PHP 庫
下面是使用PHPWord庫生成Word文檔的基本步驟:
1、使用 composer 安裝PHPWord庫,也可以這幾上去github下載,這里就不多說了。
composer require phpoffice/phpword
2、在你的PHP腳本中,引入PHPWord庫的自動加載器:
require_once 'vendor/autoload.php';
3、創(chuàng)建一個(gè)新的Word文檔對象:
$phpWord = new \PhpOffice\PhpWord\PhpWord();
4、添加文本到文檔:
$section = $phpWord->addSection(); $section->addText('你的文本內(nèi)容');
5、保存文檔為Word文件:
$phpWord->save('path/to/save.docx');
以上是一個(gè)簡單的示例,你可以根據(jù)自己的需求進(jìn)一步探索PHPWord庫的其他功能和選項(xiàng),例如添加樣式、表格、圖片等。
總結(jié)一下,通過使用PHPWord庫,你可以輕松地在PHP中生成Word文檔。記得在開始之前安裝PHPWord庫,并按照上述步驟編寫你的PHP代碼。這樣,你就可以根據(jù)自己的需求生成自定義的Word文檔了。
完整的PHPWord 庫的基本使用示例
require_once 'bootstrap.php'; // 創(chuàng)建新文檔... $phpWord = new \PhpOffice\PhpWord\PhpWord(); /* 注意:附加到文檔的任何元素都必須位于節(jié)內(nèi). */ // 添加一個(gè)空的Section到文檔... $section = $phpWord->addSection(); // 將 Text 元素添加到默認(rèn)字體樣式的部分... $section->addText( '"從昨天學(xué)習(xí),為今天生活,為明天祈禱。 ' . '重要的是不要停止質(zhì)疑。" ' . '(文章內(nèi)容)' ); /* * 注意:可以通過三種方式自定義添加的文本元素的字體樣式: * - 內(nèi)聯(lián); * - 使用命名字體樣式(將隱式創(chuàng)建新的字體樣式對象); * - 使用顯式創(chuàng)建的字體樣式對象。 */ // 添加帶有自定義字體的內(nèi)聯(lián)文本元素... $section->addText( '"偉大的成就通常源于巨大的犧牲, ' . '并且絕不是自私的結(jié)果。" ' . '(文章內(nèi)容)', array('name' => 'Tahoma', 'size' => 10) ); // 添加使用命名字體樣式自定義字體的文本元素... $fontStyleName = 'oneUserDefinedStyle'; $phpWord->addFontStyle( $fontStyleName, array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true) ); $section->addText( '"最大的成就不是永不跌倒,' . '而是在跌倒后再次站起來。" ' . '(文章內(nèi)容)', $fontStyleName ); // 添加使用顯式創(chuàng)建的字體樣式對象自定義字體的文本元素... $fontStyle = new \PhpOffice\PhpWord\Style\Font(); $fontStyle->setBold(true); $fontStyle->setName('Tahoma'); $fontStyle->setSize(13); $myTextElement = $section->addText('"相信你可以,你就已經(jīng)成功了一半。" (文章內(nèi)容)'); $myTextElement->setFontStyle($fontStyle); // 將文檔保存為 OOXML 文件... $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save('helloWorld.docx'); // 將文檔保存為 ODF 文件... $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText'); $objWriter->save('helloWorld.odt'); // 將文檔保存為 HTML 文件... $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML'); $objWriter->save('helloWorld.html'); /* 注意:我們跳過 RTF,因?yàn)樗皇腔?nbsp;XML 的并且需要不同的示例。*/ /* 注意:我們跳過 PDF,因?yàn)槭褂谩癏TML-to-PDF”方法來創(chuàng)建 PDF 文檔。*/ // 更多示例,可以查看 PHPWORD 官方文檔
2、利用windows下面的 com組件
使用windows下的com組件,com作為PHP的一個(gè)擴(kuò)展類,安裝過office的服務(wù)器會自動調(diào)用word.application的com,可以自動生成文檔,PHP官方文檔手冊查看具體說明(https://www.php.net/manual/en/class.com.php)
示例代碼如下
<?php // starting word $word = new COM("word.application") or die("Unable to instantiate Word"); echo "Loaded Word, version {$word->Version}\n"; //bring it to front $word->Visible = 1; //open an empty document $word->Documents->Add(); //do some weird stuff $word->Selection->TypeText("This is a test..."); $word->Documents[1]->SaveAs("Useless test.doc"); //closing word $word->Quit(); //free the object $word = null; ?>
個(gè)人建議:com實(shí)例后的方法都需要查找官方文檔才知道什么意思,個(gè)人覺得不是太方便,另外這個(gè)效率也不是很高,不推薦使用。
3、使用 php html網(wǎng)頁導(dǎo)出Word文檔
說明原理
一般情況下,有兩種方法可以導(dǎo)出doc文檔。
一種方法是使用com,并將其作為PHP的一個(gè)擴(kuò)展庫安裝到服務(wù)器上。然后,創(chuàng)建一個(gè)com對象并調(diào)用其方法。安裝了Office套件的服務(wù)器可以調(diào)用一個(gè)名為"word.application"的com對象,利用它可以生成Word文檔。但是,我不推薦這種方法,因?yàn)閳?zhí)行效率比較低(我進(jìn)行了一些測試,發(fā)現(xiàn)在執(zhí)行代碼時(shí),服務(wù)器會真實(shí)地打開一個(gè)Word客戶端)。理想情況下,com對象應(yīng)該是無界面的,在后臺進(jìn)行數(shù)據(jù)轉(zhuǎn)換,這樣效果會更好。但是,這些擴(kuò)展一般都需要付費(fèi)。
第二種方法則是直接用PHP將我們的文檔內(nèi)容寫入一個(gè)后綴為.doc的文件中。這種方法不依賴于第三方擴(kuò)展,并且執(zhí)行效率較高。
Word本身具備很強(qiáng)大的功能,它可以打開HTML格式的文件,并且能夠保留格式,即使后綴名為.doc,它也能正常識別。這為我們提供了方便。然而,在HTML格式的文件中,圖片只是鏈接,而真正的圖片文件是保存在其他地方的。也就是說,如果將HTML格式直接寫入.doc文件中,其中就不會包含圖片。那么,我們?nèi)绾蝿?chuàng)建帶有圖片的Word文檔呢?我們可以使用與HTML相似的MHT格式。
MHT格式與HTML非常相似,唯一的區(qū)別在于MHT格式中,外部鏈接引入的文件(如圖片、JavaScript、CSS)會被Base64編碼存儲。因此,單個(gè)MHT文件就能保存網(wǎng)頁中的所有資源。當(dāng)然,相比HTML,MHT文件的尺寸會更大。
Word能否識別MHT格式呢?我將一個(gè)網(wǎng)頁保存為MHT格式,然后將后綴名修改為.doc,并用Word打開,結(jié)果是OK,Word也能正常識別MHT文件并顯示其中的圖片。
好了,既然Word可以識別MHT格式,接下來我們就考慮如何將圖片插入到MHT中。由于HTML代碼中的圖片路徑保存在img標(biāo)簽的src屬性中,只需要提取HTML代碼中的src屬性值,就能獲取到圖片的地址。即使是相對路徑,也可以加上URL的前綴,轉(zhuǎn)換為絕對路徑。一旦有了圖片地址,我們就可以使用file_get_content函數(shù)獲取到圖片文件的實(shí)際內(nèi)容,然后調(diào)用base64_encode函數(shù)將文件內(nèi)容編碼為Base64編碼,最后將其插入到MHT文件的適當(dāng)位置即可。
最后,我們有兩種方法將文件發(fā)送給客戶端。一種方法是先在服務(wù)器端生成一個(gè).doc文檔,并記錄下這個(gè)文檔的地址;最后,通過header("location:xx.doc")將文檔地址發(fā)送給客戶端,讓客戶端下載該文檔。另一種方法是直接發(fā)送HTML請求,修改HTML協(xié)議頭部,將content-type設(shè)置為application/doc,并將content-disposition設(shè)置為attachment,后面跟上文件名。在發(fā)送完HTML協(xié)議以后,直接將文件內(nèi)容發(fā)送給客戶端,也可以讓客戶端下載該.doc文件。
完整示例封裝函數(shù)代碼
/** * 根據(jù)HTML代碼獲取word文檔內(nèi)容 * 創(chuàng)建一個(gè)本質(zhì)為mht的文檔,該函數(shù)會分析文件內(nèi)容并從遠(yuǎn)程下載頁面中的圖片資源 * 該函數(shù)依賴于類MhtFileMaker * 該函數(shù)會分析img標(biāo)簽,提取src的屬性值。但是,src的屬性值必須被引號包圍,否則不能提取 * * @param string $content HTML內(nèi)容 * @param string $absolutePath 網(wǎng)頁的絕對路徑。如果HTML內(nèi)容里的圖片路徑為相對路徑,那么就需要填寫這個(gè)參數(shù),來讓該函數(shù)自動填補(bǔ)成絕對路徑。這個(gè)參數(shù)最后需要以/結(jié)束 * @param bool $isEraseLink 是否去掉HTML內(nèi)容中的鏈接 */ 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(); //這個(gè)算法要求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變量應(yīng)該是HTML源代碼,后面的鏈接應(yīng)該是能填補(bǔ)HTML代碼中圖片相對路徑的URL地址
注意,在使用這個(gè)函數(shù)之前,您需要先包含類MhtFileMaker,這個(gè)類可以幫助我們生成Mht文檔。
MhtFileMaker類
<?php 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; } } ?>
4、使用純html格式導(dǎo)出WORD
利用ob_start把html頁面先存儲起來(解決一下頁面多個(gè)header問題,可以批量生成),然后在寫入doc文檔內(nèi)容利用文章來源:http://www.zghlxwxcb.cn/article/432.html
示例代碼
<?php class word { function start() { ob_start(); 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">'; } function save($path) { echo "</html>"; $data = ob_get_contents(); ob_end_clean(); $this->wirtefile ($path,$data); } function wirtefile ($fn,$data) { $fp=fopen($fn,"wb"); fwrite($fp,$data); fclose($fp); } } $html = '<table width=600 cellpadding="6" cellspacing="1" bgcolor="#336699"> <tr bgcolor="White"> <td>Toy模板網(wǎng)</td> <td>這是文章內(nèi)容...這是文章內(nèi)容...這是文章內(nèi)容</td> </tr> <tr bgcolor="red"> <td>Toy模板網(wǎng)</td> <td>這是文章內(nèi)容...這是文章內(nèi)容...這是文章內(nèi)容</td> </tr> <tr bgcolor="White"> <td colspan=2 > Toy模板網(wǎng)<br> 最靠譜的PHP技術(shù)博客分享網(wǎng)站 <img src="http://www.zghlxwxcb.cn/style/defalut/img/logo.png"> </td> </tr> </table> '; //批量生成 for($i=1;$i<=3;$i++){ $word = new word(); $word->start(); //$html = "aaa".$i; $wordname = 'Toy模板網(wǎng)'.$i.".doc"; echo $html; $word->save($wordname); ob_flush();//每次執(zhí)行前刷新緩存 flush(); }
文章來源地址http://www.zghlxwxcb.cn/article/432.html
到此這篇關(guān)于如何使用php生成word文檔的文章就介紹到這了,更多相關(guān)內(nèi)容可以在右上角搜索或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!