LoginSignup
2
1

More than 3 years have passed since last update.

PHPWordテンプレートに改行を含む文字列をセットする

Posted at

やりたいこと

PHPOffice/PHPWord のテンプレートに、改行を含む文字列をセットしたい。

解決方法

改行文字を <w:br /> に置換してセットする。

<?php
use PhpOffice\PhpWord;

$phpWord = new PhpWord\PhpWord();

// テンプレートファイルの読み込み
$templateProcessor = new PhpWord\TemplateProcessor('/path/to/template/file.docx');

// テンプレートにセットする値
$rawValues = [
    'foo' => "bar\nbuz\n",
];

foreach ($rawValues as $key => $value) {
    // 改行文字を <w:br /> に置換する
    $processedValues[$key] = preg_replace('/\n/', '<w:br />', $value);
}

// テンプレートに値をセットする
$templateProcessor->setValues($processedValues);

// ファイルを保存する
$templateProcessor->saveAs('/path/to/save/file.docx');

備考

思わぬデザイン崩れの原因にもなりやすいので、できるだけセットする文字列に改行文字を含まない構成を検討したほうがよいと思います。

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1