PHP HTML生成word

/**

  • 根據HTML代碼獲取word文檔內容
  • 創建一個本質爲mht的文檔,該函數會分析文件內容並從遠程下載頁面中的圖片資源
  • 該函數依賴於類WordMake
  • 該函數會分析img標籤,提取src的屬性值。但是,src的屬性值必須被引號包圍,否則不能提取
  • @param string $content HTML內容
  • @param string $absolutePath 網頁的絕對路徑。如果HTML內容裏的圖片路徑爲相對路徑,那麼就需要填寫這個參數,來讓該函數自動填補成絕對路徑。這個參數最後需要以/結束
  • @param bool $isEraseLink 是否去掉HTML內容中的鏈接
    */
    // 手動下載下Wordmaker

function WordMake( $content , $absolutePath = "" , $isEraseLink = true )
{
import("ORG.Util.Wordmaker");
$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();
}

function GenerateWord($content){
$_path='Uploads/word/'.date('Y-m-d',time()).'/';
if (!file_exists($_path)){ mkdir ($_path); }
$content = iconv("utf-8", "GBK",$content);
$rand=rand(1000,9999);

$fileContent = WordMake($content,$url);//生成word內容

$fp = fopen($_path.$name.time().$rand.".doc", 'w');//打開生成的文檔
fwrite($fp, $fileContent);//寫入包保存文件
fclose($fp);
return $_path.$name.time().$rand.".doc";

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章