需求:word 导入问卷
背景:运营那里有几百个 word 格式问卷,如果去后台手动录入,无疑工作量很大,希望能直接导入。
心情:接到需求之后五味杂陈,因为以前做过 excel 导入,而且有现成的插件,代码也是一搜索一堆。
word 导入无疑涉及到了知识盲点,但是需求就在那里,又怼不过产品同学!只能硬着头皮上了。
难点:word 不好读取内容,内容读出来不好结构化。
解决问题思路:
先读取 word, 再说怎么结构化。
读取 word:
一开始想着用 phpword, 毕竟 phpoffice 这么成熟的插件应该可以直接读取到 word 内容吧。
然而现实很骨感,找遍了文档并没有找到直接读取到 word 内容的方法。phpword 只提供了把 word 转换成 html,tdf 的方法。
转换思路:
既然不能读取 word, 那我可以读取 html, 只需要把 word 转换成 html 就可以了,然后读取 html 内容就行。
代码:
<?phpnamespace 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
结果:
以上就是用php换个思路读取word内容的详细内容。