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

__EOF__

本文作者coding在路上
本文链接https://www.cnblogs.com/zyilong/p/php_read_word.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   coding在路上~  阅读(620)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示