【问题标题】:How to extract text from a Word doc / docx and perform logic using PHP如何从 Word doc / docx 中提取文本并使用 PHP 执行逻辑
【发布时间】:2020-02-07 07:31:02
【问题描述】:

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

此外,文件将包含类似结构的表格,大部分时间也会吐出边框的垂直线。

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

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

【问题讨论】:

  • 也许您应该使用 CloudConvert 等在线工具将 doc/docx 文件(无法在 PHP 中解析)转换为简单的 TXT 文件(使用正则表达式等轻松解析)。有一个简单的 API 可以访问 CC 功能,我正在使用它。很遗憾你必须用 doc/docx 文档(不是文本格式)来做事

标签: php laravel docx doc


【解决方案1】:

对于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

来抓取所需的文本

【讨论】:

    猜你喜欢
    • 2013-10-30
    • 2011-07-29
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多