如何将.docx中的换行符转换为HTML中的换行符使用PHP
问题描述:
我正在使用zip_read()
读取.docx文件,我意识到在.docx中,分页符的编码为<w:br w:type="page"></w:br>
。我想将它变成<br style="page-break-before: always">
,这样我就可以将它输出到HTML中。我怎样才能做到这一点?谢谢!如何将.docx中的换行符转换为HTML中的换行符使用PHP
答
这是一个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解析器来处理它。
'str_replace'如何? – rtfm
似乎不起作用 – user2335065
我们无法猜测您的代码。 – rtfm