关于php: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

后果:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理