微信公众号最佳实践 ( 7.1)天气预报
天气预报
中国天气网的api申请很困难,可以使用百度天气的api,weather2.php为百度天气接口代码
index.php
weather2.php
<?php
//var_dump(getWeatherInfo("桃江"));
function getWeatherInfo($cityName)
{
if ($cityName == "" || (strstr($cityName, "+"))){
return "发送天气加城市,例如天气深圳";
}
//1a3cde429f38434f1811a75e1a90310c
$ak = 1a3cde429f38434f1811a75e1a90310c;
$sk = ;
$url = http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sn=%s;
$uri = /telematics/v3/weather;
$location = $cityName;
$output = json;
$querystring_arrays = array(
ak => $ak,
location => $location,
output => $output
);
$querystring = http_build_query($querystring_arrays);
$sn = md5(urlencode($uri.?.$querystring.$sk));
$targetUrl = sprintf($url, $ak, urlencode($location), $output, $sn);
// var_dump($targetUrl);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
if ($result["error"] != 0){
return $result["status"];
}
$curHour = (int)date(H,time());
$weather = $result["results"][0];
$weatherArray[] = array("Title" =>$weather[currentCity]."天气预报", "Description" =>"", "PicUrl" =>"", "Url" =>"");
for ($i = 0; $i < count($weather["weather_data"]); $i++) {
$weatherArray[] = array("Title"=>
$weather["weather_data"][$i]["date"]."
".
$weather["weather_data"][$i]["weather"]." ".
$weather["weather_data"][$i]["wind"]." ".
$weather["weather_data"][$i]["temperature"],
"Description"=>"",
"PicUrl"=>(($curHour >= 6) && ($curHour < 18))?$weather["weather_data"][$i]["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"], "Url"=>"");
}
return $weatherArray;
}
?>
