php读取word中的内容
生活随笔
收集整理的這篇文章主要介紹了
php读取word中的内容
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.composer安裝相關的包文件
composer require phpoffice/phpword2.代碼
<?php namespace app\controller;use app\BaseController; use PhpOffice\PhpWord\PhpWord; use PhpOffice\PhpWord\IOFactory;class Word extends BaseController {public function index(){$file ="./1.docx";if ($this->getExt($file) != "docx") {return false;}$result = $this->readWordToHtml($file);return show(1,"OK",$result);}public function getExt( $file_name ){$extend = pathinfo ( $file_name );$extend = strtolower ( $extend [ "extension" ]);return $extend ;}public function getFilename( $file_name ){$pathinfo = pathinfo ( $file_name );$filename = ( $pathinfo [ "filename" ]);return $filename ;}public function readWordToHtml($source){$phpWord = \PhpOffice\PhpWord\IOFactory::load($source);$html = '';foreach ($phpWord->getSections() as $section) {foreach ($section->getElements() as $ele1) { // $paragraphStyle = $ele1->getParagraphStyle(); // if ($paragraphStyle) { // $html .= '<p style="text-align:'. $paragraphStyle->getAlignment() .';text-indent:20px;">'; // } else { // $html .= '<p>'; // }if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {foreach ($ele1->getElements() as $ele2) {if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {$html .= mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8'); // $style = $ele2->getFontStyle(); // $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8'); // $fontSize = $style->getSize(); // $isBold = $style->isBold(); // $styleString = ''; // $fontFamily && $styleString .= "font-family:{$fontFamily};"; // $fontSize && $styleString .= "font-size:{$fontSize}px;"; // $isBold && $styleString .= "font-weight:bold;"; // $html .= sprintf('<span style="%s">%s</span>', // $styleString, // mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8') // );} elseif ($ele2 instanceof \PhpOffice\PhpWord\Element\Image) { // $imageSrc = 'images/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension(); // $imageData = $ele2->getImageStringData(true); // // $imageData = 'data:' . $ele2->getImageType() . ';base64,' . $imageData;file_put_contents($imageSrc, base64_decode($imageData)); // $html .= '<img src="'. $imageSrc .'" style="width:100%;height:auto">';}}} // $html .= '</p>';}}return mb_convert_encoding($html, 'UTF-8', 'GBK');}}3.結果:
?
總結
以上是生活随笔為你收集整理的php读取word中的内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: uniapp一键登陆(php)
- 下一篇: php读取pdf文件