用PHP换个思路读取WORD内容
项目:问卷
需求:WORD 导入问卷
背景:运营那里有几百个 WORD 格式问卷,如果去后台手动录入,无疑工作量很大,希望能直接导入。
心情:接到需求之后五味杂陈,因为以前做过 excel 导入,而且有现成的插件,代码也是一搜索一堆。
word 导入无疑涉及到了知识盲点,但是需求就在那里,又怼不过产品同学!只能硬着头皮上了。
难点:word 不好读取内容,内容读出来不好结构化。
解决问题思路:
先读取 WORD, 再说怎么结构化。
读取 WORD:
一开始想着用 PHPWORD, 毕竟 PHPOFFICE 这么成熟的插件应该可以直接读取到 WORD 内容吧。
然而现实很骨感,找遍了文档并没有找到直接读取到 WORD 内容的方法。PHPWORD 只提供了把 WORD 转换成 HTML,TDF 的方法。
转换思路:
既然不能读取 WORD, 那我可以读取 HTML, 只需要把 WORD 转换成 HTML 就可以了,然后读取 HTML 内容就行。
代码:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpWord\Reader\Word2007;
class Test extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'word';
/**
* The console command description.
*
* @var string
*/
protected $description = 'word';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle(Word2007 $word) {
//WORD转换HTML
$result=$word->load(storage_path('测试.docx'));
$write=new \PhpOffice\PhpWord\Writer\HTML($result);
$write->save(storage_path().'/测试.html');
//读取HTML内容
$document=new \DOMDocument();
$document->loadHTML(file_get_contents(storage_path('测试.html')));
$html=simplexml_import_dom($document);
dd((array)$html->body);
}
}
开始测试:新建 测试.docx
测试.docx 内容:
执行脚本:
php artisan word
结果:
本文出至:学新通
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通
- 本文地址: https://www.swvq.com/boutique/detail/15802
- 联系方式: luke.wu@swvq.com
- 来源链接: www.php.cn/php-weizijiaocheng-481321.html
系列文章
更多
同类精品
更多
精彩评论
-
windows上查看nginx是否启动
PHP中文网 04-19 -
2023年最新的28道PHP面试题附答案
PHP中文网 03-27 -
navicat怎样清除注册表
PHP中文网 04-05 -
推荐五款xml编辑工具
PHP中文网 03-04 -
docker hub 进不去怎么办
PHP中文网 03-15 -
ChatGPT应用通过Axios+EventSource使用GPT3.5 API
uWydnA 03-13 -
强力推荐10款好看使用的Bootstrap后台管理系统模板
PHP中文网 03-09 -
vscode怎么调整代码大小两种方法
PHP中文网 03-11 -
navicat连接sqlserver数据库
PHP中文网 04-03 -
navicat删除的数据能还原吗
PHP中文网 04-09