PHP讀取WORD內容

LiuXiaoKang發表於2021-08-26

專案:問卷
需求: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

結果:

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章