PHPWord如何使用模板製作Word
PHPWord需要透過Composer進行安裝.
下載Composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
下載最新版本的PHPWord
composer require phpoffice/phpword
可以編輯composer.json,下載需要的版本.
{
"config": {
"platform-check": false
},
"require": {
"phpoffice/phpword": "v0.16.*"
}
}
另外可以關閉platform-check,避免在執行程式出現下方錯誤訊息.
Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 7.3.0".
接著執行
composer update
準備Word模板,並把要替換的資料改成 ${search-pattern}
require_once 'bootstrap.php';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('Templates/myWord.docx');
$templateProcessor->setValue('Title', 'This is myWord');
$templateProcessor->setValue('Name', 'Shock');
$templateProcessor->setImageValue('Image', '11091183_807879772636870_3788721645699854513_n.jpg');
$templateProcessor->saveAs('myWordResult.docx');
用 TemplateProcessor 載入模板檔案
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('Templates/myWord.docx');
設定值,將${Title}替換成This is myWord,${Name}替換成Shock.
$templateProcessor->setValue('Title', 'This is myWord');
$templateProcessor->setValue('Name', 'Shock');
設定圖片
$templateProcessor->setImageValue('Image', '11091183_807879772636870_3788721645699854513_n.jpg');
圖片可設定參數
${search-image-pattern}
${search-image-pattern:[width]:[height]:[ratio]}
${search-image-pattern:[width]x[height]}
${search-image-pattern:size=[width]x[height]}
${search-image-pattern:width=[width]:height=[height]:ratio=false}
留言
張貼留言