PHP word上传转换到富文本编辑器 含word的图片上传

基于 phpword 详情移步  https://github.com/PHPOffice/PHPWord

以下代码主要基于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 == '') {
                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 ,看自己选择

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
PHPWord Beta 0.6.2 开发者指南 目 录 首先我们要了解文档最基本的信息和设置: 4 计量单位:缇(twips) 4 字体设置 4 文档属性设置 4 新建文档 5 添加页面 5 页面样式 5 页面样式属性 6 文本 7 添加文本 7 添加文本资源 7 文本样式 8 样式属性列表 9 添加换行符 10 添加分页符 10 列表 10 添加列表 10 列表样式 11 列表样式属性列表 11 超链接 11 添加超链接 11 超链接样式 12 图片 13 添加图片 13 图片样式 13 图片样式属性 13 添加GD生成图片 14 添加水印 14 添加对象 15 添加标题 15 添加目录 16 表格 17 添加表格 17 添加行 17 添加单元格 17 单元格样式 19 表格样式 20 页脚 22 页眉 23 模版 23 其他问题修改 25 解决文本缩进问题 25 表格对齐和表格缩进 27 图片缩进和绝对相对悬浮定位 30 首先我们要了解文档最基本的信息和设置:  因为是国外编辑的类库,存在对中文支持的问题,使用前,我们需要进行一些修正: 1、解决编码问题,PHPword 会对输入的文字进行utf8_encode编码转化,如果你使用GBK、GB2312或者utf8编码的话就会出现乱码,如果你用utf8编码,就查找类库中所有方法中的 utf8_encode 转码将其删除,如果你采用GBK或者GB2312编码,使用iconv进行编码转换。 2、解决中文字体支持,在writer/word2007/base.php中 312行添加 $objWriter->writeAttribute('w:eastAsia',$font) 3、启动php zip支持,windows环境下在php配置文件php.ini中,将extension=php_zip.dll前面的分号“;”去除;(如果没有,请添加extension=php_zip.dll此行并确保php_zip.dll文件存在相应的目录),然后同样在php.ini文件中,将 zlib.output_compression = Off 改为zlib.output_compression = On ; 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值