<?php
//下面的只是做固定城市的天气情况调用
//如果需要根据地点定位需要从http://www.nmc.cn/rest/province/获取省市代码再自行开发
//json数据源是http://www.nmc.cn/rest/weather?stationid=城市代码
//先去中央气象台找一下省 http://www.nmc.cn/rest/province/
//找到省再找下市,比如这里是山东:http://www.nmc.cn/rest/province/ASD
//然后复制城市代码,这里是58024
// {
// "code": "58024",
// "province": "山东省",
// "city": "枣庄",
// "url": "/publish/forecast/ASD/zaozhuang.html"
// },
header("Content-Type: text/html; charset=utf-8");
$date=date('Y-m-d');
$tomorrow = date('Y-m-d', strtotime($date . ' +1 day'));
$url='http://www.nmc.cn/rest/weather?stationid=城市代码';
//如果对精度要求没那么高可以每天上午下载一次该json到本地,避免下午时候天气出现9999;
//$url = 'data/weather.json';
$jsonData = file_get_contents($url);
$data = json_decode($jsonData, true);
// 解析JSON,第二个参数为true返回关联数组
$pt=$data["data"]["predict"]["publish_time"];
//无效代码,测试用的
// 处理多级数据
foreach ($data["data"]["predict"]["detail"] as $item) {
if ($item['date'] == $date) {
// 条件判断
$day_info=$item["day"] ["weather"]["info"];
$night_info=$item["night"]["weather"]["info"];
$day_temp=$item["day"] ["weather"]["temperature"];
$night_temp=$item["night"]["weather"]["temperature"];
//下午时上午的天气数据会变成9999,所以要判断一下
if($day_info=='9999') {
//如果day的数据是9999的话,就只显示night的数据
$dweather = "今天:".$night_info.$night_temp."℃";
}
if($day_info!=='9999') {
//这里是天气的格式
$dweather= "今天白天:".$day_info.$day_temp."℃ 晚间:".$night_info.$night_temp."℃";
}
// echo $dweather;
}
if ($item['date'] == $tomorrow) {
// 明天的天气
$tdayinfo=$item["day"] ["weather"]["info"];
$tniginfo=$item["night"]["weather"]["info"];
$tdaytemp=$item["day"] ["weather"]["temperature"];
$tnigtemp=$item["night"]["weather"]["temperature"];
if($tdayinfo=='9999') {
$tweather = "明天:". $tniginfo.$night_temp."℃";
}
if($tdayinfo!=='9999') {
$tweather= "明天白天:".$tdayinfo.$tdaytemp."℃ 晚间:".$tniginfo.$tnigtemp."℃";
}
// echo $tweather;
}
}
?>
PHP获取固定的城市天气;使用中央气象台免费api
于 2024-05-23 08:59:23 首次发布