PHPword上传转换到富⽂本编辑器含word的图⽚上传以下代码主要基于thinkphp 所以部分代码需要优化
use OSS\Core\OssException;
use OSS\OssClient;
use PhpOffice\PhpWord\IOFactory;
use think\Config;
use think\File;
/**
* Class WordUpload
* @package app\common\util
* word ⽂档上传
*/
class WordUpload
{
private $file;
private $size;
private $ext;
private $savePath = '/upload/word/';
private $errorMsg;
private $delTmp = true;
/**
* WordUpload constructor.
* @param $file [上传的⽂件]
* @param int $size [⽂件⼤⼩]
* @param string $ext [允许的后缀]
*/
public function __construct($file, $size = 5242880, $ext = 'docx')
{
$this->file = $file;
$this->size = $size;
$this->ext = $ext;
}
public function getHtml()
{
$file = request()->file($this->file);
if (!$file instanceof File) {
$this->errorMsg = '请上传⽂件';
return false;
}
//上传⽂件
$info = $file->validate(['size'=>$this->size,'ext'=>$this->ext])->move(ROOT_PATH . $this->savePath);
if(!$info){
// 上传失败获取错误信息
$this->errorMsg = $file->getError();
return false;
}
try {
//获取⽂件路径
$tempDocx = ROOT_PATH . $this->savePath . $info->getSaveName();
$objWriter = IOFactory::createWriter(IOFactory::load($tempDocx), 'HTML');
$tempHtml = ROOT_PATH . $this->savePath .substr($info->getSaveName(), 0, strpos($info->getSaveName(), '.')) . '.html';
$objWriter->save($tempHtml);
$html = file_get_contents($tempHtml);
if ($this->delTmp) {
//删除临时⽂件
register_shutdown_function(function () use ($tempHtml, $tempDocx){
unlink($tempHtml);
unlink($tempDocx);
});
}
$html = $this->getHtmlBody($html);
if ($html == '') {
免费图片编辑软件app
throw new \Exception('上传⽂件内容为空');
}
$html = $this->saveImage($html);
$html = $this->clearStyle($html);
$html = $this->clearSpan($html);
} catch (\Exception $e) {
$this->errorMsg = $e->getMessage();
return false;
}
return $html;
}
/**
* @param $html
* @return string
* 匹配出body的内容
*/
private function getHtmlBody($html) {
preg_match('/<body>([\s\S]*)<\/body>/', $html,$matches);
return isset($matches[1]) ? $matches[1] : '';
}
/**
* @param $html
* @return mixed
* 图⽚处理
*/
private function saveImage($html)
{
/
/匹配图⽚
preg_match_all('/<img[^>]*src="([\s\S]*?)"\/>/', $html,$imageMatches);
if (!$imageMatches[1]) {
return $html;
}
$imageUrl = [];
foreach ($imageMatches[1] as $image) {
$imageUrl[] = $this->saveOssBase64Image($image);
}
return str_replace($imageMatches[1], $imageUrl, $html);
}
/
**
* @param $base64_image_content
* @return string
* 保存图⽚到本地
*/
private function saveLocalBase64Image($base64_image_content){
$imge_web_url = '';
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
//图⽚后缀
$type = $result[2];
//保存位置--图⽚名
$image_name = date('His') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT). '.' . $type;            $image_file_path = $this->savePath .'image/'.date('Ymd');
$image_file = ROOT_PATH . $image_file_path;
$imge_real_url = $image_file . DS . $image_name;
$imge_web_url = $image_file_path .  DS . $image_name;
if (!file_exists($image_file)){
mkdir($image_file, 0700, true);
}
//解码
$decode = base64_decode(str_replace($result[1], '', $base64_image_content));            file_put_contents($imge_real_url, $decode);
return $imge_web_url;
}
return $imge_web_url;
}
/**
* @param $content
* @return string
* 上传图⽚到阿⾥云OSS
*/
private function saveOssBase64Image($content)
{
$url = '';
preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result);
$ossConfig = Config::get('oss');
foreach ($ossConfig as $key=>$value) {
${$key} = $value;
}
// 设置⽂件名称。
$object = date("Y-m-d"). '/' .  md5(microtime(true)) . '.' . $result[2];
$content = base64_decode(str_replace($result[1], '', $content));
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$result = $ossClient->putObject($bucket, $object, $content);
$url = $result['oss-request-url'];
} catch(OssException $e) {
}
return $url;
}
/**
* @param $content
* @return null|string|string[]
* 清除p,span标签的样式
*/
private function clearStyle($content)
{
$patterns = array (
'/<(p|span)[\s\S]*?>/i',
);
return preg_replace($patterns, '<$1>', $content);
}
/**
* @param $content
* @return null|string|string[]
* 清除span标签
*/
private function clearSpan($content)
{
$patterns = array (
'/<span[\s\S]*?>/i',
'/<\/span>/i',
);
return preg_replace($patterns, '', $content);
}
/**
* @return mixed
*/
public function getErrorMsg()
{
return $this->errorMsg;
}
}
使⽤⽅式
$upload = new WordUpload('file');
$html = $upload->getHtml();
if ($html === false) {
$this->error($upload->getErrorMsg());
}
$this->success('上传成功', '', $html);
可以去除 p标签,span标签内的样式
还可以去除span标签
当然还可以扩展其他的
图⽚上传 实现了上传到本地或者阿⾥云oss ,看⾃⼰选择