如何使用PHP将.docx中的换行符转换为HTML中的换行符

时间:2017-10-19 03:58:38

标签: php regex preg-replace

我正在使用.animate{ width: value; height: value; /* css transition effects here */ } 阅读.docx文件,我意识到在.docx中,分页符的编码为zip_read()。我想把它变成<w:br w:type="page"></w:br>所以我可以将它输出到HTML中。我怎样才能做到这一点?谢谢!

1 个答案:

答案 0 :(得分:0)

这是一种XML文件格式,因此您可以使用DOM读取它:

$xml = <<< WORD
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
  <w:body>
    <w:br w:type="page"></w:br>
  </w:body>
</w:wordDocument>
WORD;

libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadXML($xml);
libxml_clear_errors();

$xpath = new DOMXPath($dom);
$xpath->registerNamespace('w', 'http://schemas.microsoft.com/office/word/2003/wordml');

// find all the page breaks
foreach ($xpath->evaluate('//w:br[@w:type="page"]') as $page_break) {
    // create an html break element with some style attribute
    $html_break = $dom->createElement('br');
    $html_break->setAttribute('style', 'page-break-before: always');
    // replace the page break with the html break in the document
    $page_break->parentNode->replaceChild($html_break, $page_break);
}
echo $dom->saveHTML();

这会根据要求将单词分页符转换为html分页符:

<?mso-application progid="Word.Document"><w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
  <w:body>
    <br style="page-break-before: always">
  </w:body>
</w:wordDocument>

考虑到xml这个词的其余部分仍然是原样,这并不是很有意义。但这就是你使用XML解析器处理它的方式。

请务必查看https://github.com/PHPOffice/PHPWord