【微信公衆平臺開發】封裝獲取天氣預報功能


微信公衆平臺小功能多點,可以增加用戶的粘性,不會感覺你微信沒內容,就把你給取消關注了。所以得折騰各種有的沒的東西。

個人封裝天氣預報功能代碼如下(說明下:網上有很多此類代碼,但是要自己理解,就得實際折騰)
<?php
header('Content-Type:text/html;charset=utf-8');
class WeChatMsgType
{
	private  $toUserName;
	private  $fromUserName;
	private  $xmlModle;
	private  $createTime;
	
	public function SetUserInfo($toUserName,$fromUserName) //設置用戶信息
	{
		$this->toUserName = $toUserName;
		$this->fromUserName = $fromUserName;
		$this->createTime = time();
	}
	
	
       
	public function WeatherMsg($cityName)	//天氣預報信息
	{
		$url = "http://api.map.baidu.com/telematics/v3/weather?location=".$cityName."&output=json&ak=11ffd27d38deda622f51c9d314d46b17";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch); 
		curl_close($ch);
		$result = json_decode($output, true);
		if ($result["error"] != 0){
			return $result["status"];
		}
		$curHour = (int)date('H',time());
		
		$weather = $result["results"][0];
		
		$ImageTexts = array();
		
		$ImageTexts[0] = self::SetImageTextInfo($weather['currentCity'].'天氣預報',"", "", "");
		//$aa=var_export(urldecode(urlencode($weather)),true);
		//file_put_contents("debug.txt", date("Y-m-d H:i:s",time()).$aa.PHP_EOL,FILE_APPEND);
		for($i=0; $i<count($weather['weather_data']); $i++)
		{
			$ImageTexts[$i+1] = self::SetImageTextInfo($weather["weather_data"][$i]["date"]."\n".
            $weather["weather_data"][$i]["weather"]." ".
            $weather["weather_data"][$i]["wind"]." ".
            $weather["weather_data"][$i]["temperature"],
					"", (($curHour >= 6) && ($curHour < 18))?$weather["weather_data"][$i]["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"], "");
		}
		
		return self::ImageTextMsg($ImageTexts);
	}
	
	
	
	public function SetImageTextInfo($sTitle, $sDescription, $sPicUrl, $Url) 
	{
		$item = "<item>
				<Title><![CDATA[%s]]></Title> 
				<Description><![CDATA[%s]]></Description>
				<PicUrl><![CDATA[%s]]></PicUrl>
				<Url><![CDATA[%s]]></Url>
				</item>
				";
		$ret=sprintf($item, $sTitle, $sDescription, $sPicUrl,$Url);
		return $ret;
	}
	
	public function ImageTextMsg($ImageTexts)
	{
		$this->xmlModle = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[news]]></MsgType>
				<ArticleCount>%d</ArticleCount>
				<Articles>
				";
		foreach ($ImageTexts as $item)
		{
			$this->xmlModle = $this->xmlModle.$item;
		}
		$this->xmlModle = $this->xmlModle."</Articles></xml>" ;
		
		$ret=sprintf($this->xmlModle, $this->fromUserName, $this->toUserName, $this->createTime,count($ImageTexts));
		return $ret;
	}
}
?>

調用用法:
$weChatMsgType = new WeChatMsgType();
$weChatMsgType->SetUserInfo($this->toUserName, $this->fromUserName);
$resultStr=$weChatMsgType->WeatherMsg("北京");



注:上面ak同百度周邊搜索篇說明一樣,不懂看前面


發佈了119 篇原創文章 · 獲贊 77 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章