PHP獲取指定地區的天氣
阿新 • • 發佈:2019-01-30
在開發網站的時候用到天氣查詢,由於是基於Wordpress的 所以有很多限制,先建一個【weather.php】的檔案,然後看程式碼:
<?php //獲取天氣 $url = 'http://m.weather.com.cn/data/'; $id = '101181101'; //焦作的代號 $data = file_get_contents($url . $id .'.html'); $obj=json_decode($data); echo $obj->weatherinfo->city.':'.$obj->weatherinfo->weather1.' '.$obj->weatherinfo->temp1;
對於:
$url = 'http://m.weather.com.cn/data/';
$id = '101181101'; //焦作的代號
$data = file_get_contents($url . $id .'.html');
可簡寫為:
$data = file_get_contents('http://m.weather.com.cn/data/101181101.html');
而對於:
$obj=json_decode($data);
它是把獲取的json資料轉化為一個物件,方便呼叫;
那麼最後一句:
echo $obj->weatherinfo->city.':'.$obj->weatherinfo->weather1.' '.$obj->weatherinfo->temp1;
就是獲取指定的資料並按照一定格式輸出,
$obj->weatherinfo->city //城市
$obj->weatherinfo->weather1 //今天的天氣
$obj->weatherinfo->temp1 //今天的氣溫
其他引數可以自行訪問 http://m.weather.com.cn/data/101181101.html 檢視
最後 在需要顯示的地方
<?php include 'weather.php' ?>
即可。