獲取微信XML格式中傳來的圖片並保存到本地

微信開啓防外鏈後,一種方法是繞開外鏈,另外一種方法天然是將圖片保存到本地,在取的時候從本地去獲取圖片,那麼如何從微信返回的XML格式中獲取到圖片的地址而且下載保存呢,代碼以下:json

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;
}
相關文章
相關標籤/搜索