PHP生成word的三種方式
利用windows下面的 com組件
利用PHP將內容寫入doc文件之中
原理:com作為PHP的一個擴展類,安裝過office的服務器會自動調用word.application的com,可以自動生成文檔,PHP官方文檔手冊:http://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;
?>
個人建議:com實例後的方法都需要查找官方文檔才知道什麼意思,編輯器沒有代碼提示,非常不方便,另外這個效率也不是很高,不推薦使用
生成mht格式(和HTML很相似)寫入word
純HTML格式寫入word
/**
* 根據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();
}
這個函數的主要功能其實就是分析HTML代碼中的所有圖片地址,並且依次下載下來。獲取到了圖片的內容以後,調用MhtFileMaker類,將圖片添加到mht文件中。具體的添加細節,封裝在MhtFileMaker類中了。
*