PHP 读取word文档获取纯文本

方法一

因为doc格式的读取比较麻烦,这里采用的是基于linux环境的,通过libreoffice工具.使用php系统方法shell_exec()(需解除禁用函数)直接执行命令将doc/docx文件转为html文件,再读取html

linux命令解读:

export HOME=/tmp/ && /bin/libreoffice --headless --convert-to html file_tempName --outdir html_path
其中: file_tempName 为上传文件临时路径;/bin/libreofficelibreoffice安装位置;html_path为生成html的保存位置

代码

  function readDoc($file_tempName = '')
  {
      $basePath = 'home/www/test/upload/';
      $res = shell_exec("export HOME=/tmp/ && /bin/libreoffice --headless --convert-to html " . $file_tempName.' --outdir '.$basePath);//生成html
      $fileName = substr($file_tempName,strripos($file_tempName,'/')+1).'.html';
      $html_path = $basePath . '/' . $fileName;
      $line = file_get_contents($html_path); //读取生成的html
      //去除html/css/js标签
      $line = preg_replace( "@<script(.*?)</script>@is", "", $line);
      $line= preg_replace( "@<iframe(.*?)</iframe>@is", "", $line);
      $line= preg_replace( "@<style(.*?)</style>@is", "", $line);
      $line= preg_replace( "@<(.*?)>@is", "", $line);
      $line= html_entity_decode($line, ENT_QUOTES, 'UTF-8');
      $line= htmlspecialchars_decode($line);
      $line = str_replace(["\n","\t","\r"], "", $line);//去除换行符
      if (file_exists($html_path)) {
          unlink($html_path);//删除html文件
      }
      return $line;//返回doc中的存文本
  }

方法二(仅限docx)

通过系统方法zipdocx文件转换生成xml文件,再读取xml文件获取存文本

代码

    function readDocx($file_tempName = '')
    {
        $content = '';
        $zip = zip_open($file_tempName);
        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);
        }
        zip_close($zip);
        $content = str_replace([PHP_EOL],'',$content);
        $content = str_replace(["\n","\t","\r"], "", $content);
        $content = strip_tags($content);
        return $content;
    }
posted @ 2022-03-23 15:06  coding在路上~  阅读(559)  评论(0编辑  收藏  举报