| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <?php
- namespace common\logic\wechat;
- use common\helpers\FileHelper;
- use Yii;
- class WechatMaterialLogic
- {
- /**
- * html里面的图片转为微信公众号内部图片
- * @param string $content
- * @return array|string|string[]
- */
- public function handleMaterialImgs(string $content)
- {
- /** @var \jianyan\easywechat\Wechat $wechat */
- $wechat = Yii::$app->wechat;
- $app = $wechat->getApp();
- $preview_imgs = [];
- $pattern = "/[img|IMG].*?src=['|\"](.*?(?:[.gif|.jpg]))['|\"].*?[\/]?>/";// 表达式
- preg_match_all($pattern, $content,$match);
- if(!empty($match[1])) $preview_imgs = array_merge($preview_imgs, $match[1]);
- if ($preview_imgs) {
- Yii::error('内容里面的图片:' . json_encode($preview_imgs));
- $replace_imgs = $this->uploadMaterialImgs($app, $preview_imgs);
- Yii::error('内容上传后图片:' . json_encode($replace_imgs));
- if ($replace_imgs) {
- foreach ($replace_imgs as $select_img => $replace_img) {
- $content = str_replace($select_img, $replace_img, $content);
- }
- }
- }
- return $content;
- }
- /**
- * 上传图片到微信公众号草稿箱
- * @param $app
- * @param $outsideImgs
- * @return array
- */
- public function uploadMaterialImgs($app, $outsideImgs)
- {
- $data = [];
- foreach ($outsideImgs as $img) {
- $file = FileHelper::downFile(Yii::getAlias('@backend').'/web/uploads',md5(time()).rand(1000,9999), $img);
- $result = $app->material->uploadImage($file);
- if (!empty($result['url'])) $data[$img] = $result['url'];
- unlink($file);// 删除临时保存图片
- }
- return $data;
- }
- }
|