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

前端之家收集整理的这篇文章主要介绍了获取微信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://www.f2er.com/xml/295433.html

猜你在找的XML相关文章