获取微信XML格式中传来的图片并保存到本地

微信开启防外链后,一种方法是绕开外链,另一种方法自然是将图片保存到本地,在取的时候从本地去获取图片,那么如何从微信返回的XML格式中获取到图片的地址并且下载保存呢,代码如下:

protected function work(){
		$xml = simplexml_load_string($image_message['content'], 'SimpleXMLElement', LIBXML_NOCDATA);
		$content = json_decode(json_encode((array)$xml), TRUE);//微信的XML转成数组格式这个没什么好说的
		$wechat_img_url = $content['PicUrl'];//获取图片地址
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $wechat_img_url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
		$response= curl_exec($ch);
		if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200'){
			$img_type = @getimagesize($wechat_img_url);//getimagesize可以获取图片的格式
			if($img_type["mime"] == "image/jpeg"){
				$_filename = $image_message['id'].'.jpg';
			}elseif($img_type["mime"] == "image/png"){
				$_filename = $image_message['id'].'.png';
			}else{
					break;
			}
			$_savePath = realpath('.').'/images/message_inbox_image/old';
			$this->ensurePath($_savePath);
			$image_name = $_savePath.'/'.$_filename;
			$fp2=@fopen($image_name, "a");
			fwrite($fp2,$response);
			fclose($fp2);
		}else{
			$image_name = "";
		}
		curl_close($ch);
	}

public function ensurePath($path) {
	str_replace('\\', '/', $path);
	$dirArray = explode('/', $path);
	$dirString = '';
	foreach ($dirArray as $dirName) {
		$dirString .= $dirName . '/';
		@mkdir($dirString);
	}
	return;
}

转载于:https://my.oschina.net/wsyblog/blog/639436

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值