PHP获取固定的城市天气;使用中央气象台免费api

<?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;
	}
}
?>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BigKay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值