【问题标题】:How to extract text from docx file?如何从docx文件中提取文本?
【发布时间】:2014-02-05 06:26:11
【问题描述】:

谁能帮我从 php 中的 docx 文件中提取文本? 或者有没有为此的任何linux命令?

我可以从 pdf 和 doc 中提取文本,因此 php(或 linux 命令)中的 docx 到 pdf 或 doc 转换也适用于我。

【问题讨论】:

标签: php docx


【解决方案1】:

从 docx 中提取文本非常容易,您甚至不需要依赖项(您应该激活的 zip 模块除外)

<?php

function read_docx($filename) {
    $striped_content = '';
    $content = '';

    $zip = zip_open($filename);

    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);

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
    $striped_content = strip_tags($content);

    return $striped_content;
}


echo read_docx("textExample.docx");

感谢Muhammad's question

【讨论】:

    【解决方案2】:

    使用OpenTBS

    包含它之后..这样做..

    include_once('tbs_class.php');
    include_once('../tbs_plugin_opentbs.php');
    $TBS = new clsTinyButStrong;
    $TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN);
    $TBS->LoadTemplate('filename.docx');
    echo $string = $TBS->Source; // your docx content is now in this variable
    

    【讨论】:

      【解决方案3】:

      您可以从docx文件中提取文本,请找到以下代码,您需要安装ZipArchive文件

      public function docx_to_text($filename)
      {
          $input_file = 'tmp_file.zip';
          copy($filename, $input_file);    //copy file with path (content) to temp.zip file
      
          $xml_filename = "word/document.xml"; //content file name
          $zip_handle = new ZipArchive;
          $output_text = "";
      
          if(true === $zip_handle->open($input_file))
          {
              if(($xml_index = $zip_handle->locateName($xml_filename)) !== false)
              {
                  $xml_datas = $zip_handle->getFromIndex($xml_index);
                  $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
                  $output_text = strip_tags($xml_handle->saveXML());
              }
              else
              {
                  $output_text .="";
              }
              $zip_handle->close();
          }
          else
          {
              $output_text .="";
          }
          return $output_text;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-10-03
        • 1970-01-01
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 2013-10-30
        • 2015-10-06
        相关资源
        最近更新 更多