php將內容轉為word

赵瑛發表於2024-11-06

第一步,先對內容進行處理,html的內容不適合word,在使用phpword轉換時,只接受p和span元素,其它元素都要清除掉

$modifiedHtml 為內容

$relust = check_table($modifiedHtml,'table'); // 判斷是否存在table元素
if($relust == 1){
$modifiedHtml = table_to_div($modifiedHtml); //將內容中所有的table元素替換為p元素
}
$modifiedHtml = cleanAndReplaceHtmlWithBr($modifiedHtml);// 將內容中所有的段落標籤都替換為p標籤,並清除其它標籤,只保留<p><img><a>這三種標籤。
$modifiedHtml = imgadddomain($modifiedHtml,'https://syjx.ihwrm.com');// 給本地圖片的路徑前面加上指定的域名
$modifiedHtml = replaceAllImagesWithPlaceholder($modifiedHtml);//替換無效圖片
$modifiedHtml = replaceInvalidImages($modifiedHtml);//判斷內容中圖片是否為'jpg', 'jpeg', 'gif', 'png'
$modifiedHtml = removeImgAttributesExceptSrc($modifiedHtml);//1 順序不能錯 移除 <img> 標籤中的所有屬性,除了 src 屬性
$modifiedHtml = modifyHtmlImages($modifiedHtml);//2 判斷圖片寬是否超過600,超過的就限制在600,沒有600的就不用管
$modifiedHtml = removeNestedPElements($modifiedHtml);//3 移除多餘的p標籤
$modifiedHtml = removeUnmatchedClosingParagraphTags($modifiedHtml);//4 清除沒有對應的p元素
$modifiedHtml = extractBodyContent($modifiedHtml);//5 提取 <body> 和 </body> 之間的內容
$modifiedHtml = ensureImgTagsAreClosed($modifiedHtml);//6 用php判斷文章內容中所有的img標籤是否閉合,沒有閉合的新增一下閉合

第二步

$title =  標題;
$content = 內容;

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Html;

$phpWord = new PhpWord();
$phpWord->addFontStyle('cStyle', array('size' => 12,'name' => '宋體'));//內容樣式
$phpWord->addFontStyle('cStyle1', array('size' => 16,'name' => '宋體','color' => '#333'));//內容樣式
$phpWord->addFontStyle('cStyle2', array('size' => 12,'name' => '宋體','color' => '#ff0000'));//連結樣式
$phpWord->addFontStyle('bStyle', array('size' => 12, 'bold' => true, 'name' => '宋體'));//加粗樣式
$phpWord->addFontStyle('titlestyle', array('bold' => true,'size' => 18,'name' => '宋體'));//標題的樣式
$section = $phpWord->addSection();
$section->addTextBreak(2);
$section->addText($title,'titlestyle', ['alignment' => 'center']);
$section->addTextBreak(2);
//$section->addText($content,'cStyle1', ['alignment' => 'left']);
Html::addHtml($section, $content, false, false);
$section->addTextBreak(5);
$section->addText($datetime,'bStyle', ['alignment' => 'right']);
$section->addTextBreak(5);
$linkText = '本文連結:'.$link;
$linkUrl = $link;
$section->addLink($linkUrl, $linkText,'cStyle2');
header('pragma:public');
header('Content-type:application/vnd.ms-word;charset=utf-8;name="'.$file_name.'"');
header("Content-Disposition:attachment;filename='.$file_name.'");//attachment新視窗列印inline本視窗列印
header( 'Content-Type: image/jpeg');
ob_clean();
flush();
$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save($_SERVER['DOCUMENT_ROOT'].'/'.$file_path.'/'.$file_name);
//向瀏覽器輸出下載
$writer->save('php://output');

相關文章