通常,我們可以先做好一個樣版檔,然後再將其中我們想要修改的部份,進行變數的代換即可。
PHPWord 樣版檔的變數是用 ${} 來包覆變數名稱,例如: ${name} 或 ${ID}
// 因為我用的是 XOOPS 所以要引入 header.php ,才能用一些常數
// 如果你不是用 XOOPS ,下面的這一行就不一定要有
include "header.php";
// 因為 XOOPS 有定義好 XOOPS_PATH 這個路徑常數,如果沒有的話,你得改一下這一行
require_once XOOPS_PATH.'/Frameworks/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
$phpWord = new \PhpOffice\PhpWord\PhpWord();
// 假設我把樣版檔跟程式碼放在同一個目錄下
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('Template_01.docx');
// 進行變數代換
$templateProcessor->setValue('name', '王小明');
$templateProcessor->setValue('ID', 'A123456789');
// 不知道為啥,phpword 不讓我們直接輸出到瀏覽器,所以得先存檔
$templateProcessor->saveAs("phpword_02.docx");
// 再想辦法把他輸出到瀏覽器裏
header('Content-Type: application/vnd.ms-word');
header('Content-Disposition: attachment;filename="phpword_02.docx"');
header('Cache-Control: max-age=0');
$name = $cms_path.'/phpword_02.docx';
$fp = fopen($name, 'rb');
fpassthru($fp);
// 一定要用 exit
exit;
相關文章
1、PHPWord 的使用方法整理(一)最基本的使用方式
沒有留言:
張貼留言