如何从 Word 文档/docx 中提取文本并使用 PHP 执行逻辑

How to extract text from a Word doc / docx and perform logic using PHP

我的目标是读取上传的文档并提取某些值,如浮点数“1.20、3.9”、文本。 我尝试了几个库,但似乎都无法完成工作。

此外,这些文件大多数时候都会包含类似结构的表格,这些表格也会吐出边框的垂直线。

想到的是一些繁重的正则表达式解析逻辑...

有人有建议的解决方案吗?

对于docx文件,你可以试试这个

 $zip = zip_open($file);

                if (!$zip || is_numeric($zip)) return false;

                while ($zip_entry = zip_read($zip)) {

                    if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

                    if (zip_entry_name($zip_entry) != "word/document.xml") continue;

                    $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    zip_entry_close($zip_entry);
                } // end while

                zip_close($zip);

它会将 DOCX 文档提取为文本,因为您无法仅使用 php

中的 file_get_content

对于 DOC 文件

if (($fh = fopen($file, 'rb')) !== false) {
                $headers = fread($fh, 0xA00);

                // read doc from 0 to 255 characters
                $n1 = (ord($headers[0x21C]) - 1);

                // read doc from 256 to 63743 characters
                $n2 = ((ord($headers[0x21D]) - 8) * 256);

                // read doc from 63744 to 16775423 characters
                $n3 = ((ord($headers[0x21E]) * 256) * 256);

                //read doc from 16775424 to 4294965504 characters
                $n4 = (((ord($headers[0x21F]) * 256) * 256) * 256);

                // Total length of text in the document
                $textLength = ($n1 + $n2 + $n3 + $n4);
                ini_set('memory_limit', '-1');
                $extracted_plaintext = fread($fh, $textLength);
            }

将其转换为文本后,使用 REGEX

抓取所需文本的时间