1.composer安装相关的包文件
composer require phpoffice/phpword
2.代码
<?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.结果: