【发布时间】:2016-11-18 12:03:51
【问题描述】:
我如何阅读 docx 内容,剥离所有标签但保留在下方?
- 粗体
- 斜体
- 下划线
- 新线
以下是我从其他答案中获得的代码:
//FUNCTION :: read a docx file and return the string
// http://stackoverflow.com/questions/4587216/how-can-i-convert-a-docx-document-to-html-using-php
// https://www.jackreichert.com/2012/11/how-to-convert-docx-to-html/
function readDocx($filePath) {
// Create new ZIP archive
$zip = new ZipArchive;
$dataFile = 'word/document.xml';
// Open received archive file
if (true === $zip->open($filePath)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
// Return data without XML formatting tags
$xmldata = $xml->saveXML();
// </w:p> is what word uses to mark the end of a paragraph. E.g.
// <w:p>This is a paragraph.</w:p>
// <w:p>And a second one.</w:p>
// http://stackoverflow.com/questions/5607594/find-linebreaks-in-a-docx-file-using-php
$xmldata = str_replace("</w:p>", "\r\n", $xmldata);
$xmldata = str_replace("<w:i/>", "<i>", $xmldata);
$contents = explode('\n',strip_tags($xmldata, "<i>"));
$text = '';
foreach($contents as $i=>$content) {
$text .= $contents[$i];
}
return $text;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
$filePath = 'sample.docx';
$string = readDocx($filePath);
var_dump($string);
到目前为止,我只设法保留换行符,而不是其余的:
$xmldata = str_replace("</w:p>", "\r\n", $xmldata);
$xmldata = str_replace("<w:i/>", "<i>", $xmldata); // will get <i>Hello World <-- no closing i
有什么想法吗?
编辑:
$xmldata = preg_replace("/<w\:i\/>(.*?)<\/w\:r>/is", "<i>$1</i>", $xmldata);
$xmldata = preg_replace("/<w\:b\/>(.*?)<\/w\:r>/is", "<b>$1</b>", $xmldata);
$xmldata = preg_replace("/<w\:u (.*?)\/>(.*?)<\/w\:r>/is", "<u>$2</u>", $xmldata);
但上述解决方案存在缺陷,例如:
<w:r><w:t xml:space="preserve"><w:i/>Hello</w:t></w:r><w:r><w:t xml:space="preserve"> World</w:t></w:r>
你会注意到我正在替换 <w:i/> 和 <\/w\:r>,因为 <w:i/> 没有配对。
有更好的解决方案吗?
【问题讨论】:
标签: php domdocument docx strip-tags