WechatMaterialLogic.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace common\logic\wechat;
  3. use common\helpers\FileHelper;
  4. use Yii;
  5. class WechatMaterialLogic
  6. {
  7. /**
  8. * html里面的图片转为微信公众号内部图片
  9. * @param string $content
  10. * @return array|string|string[]
  11. */
  12. public function handleMaterialImgs(string $content)
  13. {
  14. /** @var \jianyan\easywechat\Wechat $wechat */
  15. $wechat = Yii::$app->wechat;
  16. $app = $wechat->getApp();
  17. $preview_imgs = [];
  18. $pattern = "/[img|IMG].*?src=['|\"](.*?(?:[.gif|.jpg]))['|\"].*?[\/]?>/";// 表达式
  19. preg_match_all($pattern, $content,$match);
  20. if(!empty($match[1])) $preview_imgs = array_merge($preview_imgs, $match[1]);
  21. if ($preview_imgs) {
  22. Yii::error('内容里面的图片:' . json_encode($preview_imgs));
  23. $replace_imgs = $this->uploadMaterialImgs($app, $preview_imgs);
  24. Yii::error('内容上传后图片:' . json_encode($replace_imgs));
  25. if ($replace_imgs) {
  26. foreach ($replace_imgs as $select_img => $replace_img) {
  27. $content = str_replace($select_img, $replace_img, $content);
  28. }
  29. }
  30. }
  31. return $content;
  32. }
  33. /**
  34. * 上传图片到微信公众号草稿箱
  35. * @param $app
  36. * @param $outsideImgs
  37. * @return array
  38. */
  39. public function uploadMaterialImgs($app, $outsideImgs)
  40. {
  41. $data = [];
  42. foreach ($outsideImgs as $img) {
  43. $file = FileHelper::downFile(Yii::getAlias('@backend').'/web/uploads',md5(time()).rand(1000,9999), $img);
  44. $result = $app->material->uploadImage($file);
  45. if (!empty($result['url'])) $data[$img] = $result['url'];
  46. unlink($file);// 删除临时保存图片
  47. }
  48. return $data;
  49. }
  50. }