如何使用php将docx文档转换为html?

xun*_*xun 16 html php docx

我希望能够上传MS Word文档并将其导出到我的网站中.

有没有办法实现这个目标?

Dav*_*Lin 20

//FUNCTION :: read a docx file and return the string
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

            $contents = explode('\n',strip_tags($xml->saveXML()));
            $text = '';
            foreach($contents as $i=>$content) {
                $text .= $contents[$i];
            }
            return $text;
        }
        $zip->close();
    }
    // In case of failure return empty string
    return "";
}
Run Code Online (Sandbox Code Playgroud)

ZipArchiveDOMDocument都在PHP内部,因此您无需安装/ include/require其他库.

  • 谢谢,这是完美的,但有没有办法保持格式,如粗体和斜体字 (10认同)
  • 这个答案没有提供将.docx转换为HTML的解决方案-如代码strip_tags()所示-OP专门询问如何转换为HTML (2认同)