微信公众平台开发--输入城市名称返回天气信息

在实现该功能前,需登录百度apistore获取免费的接口数据

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);
}

posted @ 2016-01-06 15:03  码动未来  阅读(641)  评论(0编辑  收藏  举报