我不知道接受的答案中的PR是否已被合并,或者事实上它在2013年是否已经可行,但无论如何,自2015年以来,如果不是更早,在initial response to #553 on GitHub中指出在段落中插入换行符的正确方法:
为段落创建一个TextRun;
通过调用TextRun本身的addTextBreak()方法向TextRun添加换行符。
这是一个函数,它将处理包含文字换行符(CR-LF ["\r\n"],LF ["\n"]或CR ["\r"])的字符串中的完整文本段落:
/**
* @param \PhpOffice\PhpWord\Element\AbstractContainer $container
* E.g. a section or table cell.
* @param string $text String with literal line breaks as CR-LF, LF or CR.
* @param string|array|\PhpOffice\PhpWord\Style\Paragraph $paragraphStyle
* @param string|array|\PhpOffice\PhpWord\Style\Font $fontStyle
*
* @return \PhpOffice\PhpWord\Element\TextRun
*/
function addTextWithLineBreaks(
\PhpOffice\PhpWord\Element\AbstractContainer $container,
$text,
$fontStyle,
$paragraphStyle
) {
$textRun = $container->addTextRun($paragraphStyle);
foreach (preg_split('/(\\r\\n?+|\\n)/',
$text,
-1,
PREG_SPLIT_DELIM_CAPTURE
) as $i => $part) {
if ($i & 1) {
$textRun->addTextBreak(1, $fontStyle, $paragraphStyle);
} else {
$textRun->addText($part, $fontStyle, $paragraphStyle);
}
}
return $textRun;
}
PHPWord(0.14.0)当前在读取Word2007文档时丢弃换行符 - 希望在1.0之前修复 - 但是在Word中打开时,上面的输出是正确的。