如何使用 PHPWord 转换或读取 .doc 文件?

How to convert, or read a .doc file with PHPWord?

提问人:Grimcall 提问时间:7/10/2023 更新时间:7/10/2023 访问量:179

问:

我已经抓取了这个网站和其他网站,但没有找到任何解决方案:我正在尝试使用 PHPOffice/PHPWord 从 .doc 文件中读取文本,但我尝试的所有代码都失败了。我可以很好地阅读 .docx 文件,只是 97-03 Word 文档给我带来了麻烦。

另一种选择是将它们转换为 .docx 或 .pdf 并阅读(这必须在没有用户干预的情况下自动完成),但我也没有找到答案。

function convertDocToDocx($docPath, $docxPath)

$phpWord = new \\PhpOffice\\PhpWord\\PhpWord();

// Load the .doc file
$docReader = \PhpOffice\PhpWord\IOFactory::createReader('Word');
$phpWord = $docReader->load($docPath);

// Save the document as .docx
$docxWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$docxWriter->save($docxPath);

}

function extractTextFromDoc($filepath)
{
$objReader = IOFactory::createReader('Word97');
$phpWord = $objReader-\>load($filepath);
$text = '';

foreach ($phpWord->getSections() as $section) {
    foreach ($section->getElements() as $element) {
        if ($element instanceof \PhpOffice\PhpWord\Element\Text) {
            $text .= $element->getText();
        }
    }
}

return $text;

}
php docx phpword phpoffice pdf-解析

评论

0赞 user1191247 7/10/2023
我不认为 PHPWord 支持旧的二进制文档格式。您可以尝试使用 LibreOffice 通过命令行进行转换。这是一个古老的相关问题

答: 暂无答案