微信公衆平臺開發--輸入城市名稱返回天氣信息

在實現該功能前,需登陸百度apistore獲取免費的接口數據git

if(strtolower($postObj->MsgType)=="text")
{
$tempalte="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$fromUser=$postObj->ToUserName;
$toUser=$postObj->FromUserName;
$time=time();

$ch = curl_init();
$url = 'http://apis.baidu.com/apistore/weatherservice/cityname?cityname='.urlencode($postObj->Content);
$header = array(
'apikey:fed1e499cbd21ec4df0140eb83f2d250',
);
// 添加apikey到header
curl_setopt($ch, CURLOPT_HTTPHEADER , $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 執行HTTP請求
curl_setopt($ch , CURLOPT_URL , $url);
$res = curl_exec($ch);
$arr=json_decode($res,true);
/*
* city: "北京", //城市
pinyin: "beijing", //城市拼音
citycode: "101010100", //城市編碼
date: "15-02-11", //日期
time: "11:00", //發佈時間
postCode: "100000", //郵編
longitude: 116.391, //經度
latitude: 39.904, //維度
altitude: "33", //海拔
weather: "晴", //天氣狀況
temp: "10", //氣溫
l_tmp: "-4", //最低氣溫
h_tmp: "10", //最高氣溫
WD: "無持續風向", //風向
WS: "微風(<10m/h)", //風力
sunrise: "07:12", //日出時間
sunset: "17:44" //日落時間
*/
$content='城市:'.$arr['retData']['city']."\n".'日期:'.$arr['retData']['date']."\n".'天氣:'.$arr['retData']['weather']."\n".'氣溫:'.$arr['retData']['temp'];
printf($tempalte,$toUser,$fromUser,$time,"text",$content);
}json

相關文章
相關標籤/搜索