用php來寫一個天氣預報的模塊
天氣數據是通過采集中國氣象網站的。本來中國天氣網站也給出了數據的API接口。以下是API的地址。返回的數據格式為json格式。
1. http://www.weather.com.cn/data/sk/101010100.html
2. http://www.weather.com.cn/data/cityinfo/101010100.html
3. http://m.weather.com.cn/data/101010100.html
URL中的數字”101010100“是城市代碼。所以可以先列出每個城市的城市代碼,然後php程序接收到了城市代碼,再去組裝URL,在通過URL來顯示該城市的實時天氣。
index.php
weatherforecast.php
<?php
header("Content-Type:text/html;charset=utf-8");
header("Cache-Control:no-cache");
if (isset($_POST['cityid'])){
$cityid=$_POST['cityid'];
$url=$url="http://www.weather.com.cn/data/sk/".$cityid.".html";
}else {
$url="http://www.weather.com.cn/data/sk/101010100.html";
}
$weatherInfo_json=file_get_contents($url);
$weatherInfo=json_decode($weatherInfo_json,true);
$cityName=$weatherInfo['weatherinfo']['city'];
$cityTemp=$weatherInfo['weatherinfo']['temp'];
$cityWd=$weatherInfo['weatherinfo']['WD'];
$cityWs=$weatherInfo['weatherinfo']['WS'];
$cityTime=$weatherInfo['weatherinfo']['time'];
$citySD=$weatherInfo['weatherinfo']['SD'];
echo $weatherinfo="城市名字:$cityName,氣溫:$cityTemp,風向:$cityWd";
?>