PHP 獲取指定地區的天氣
在開發網站的時候用到天氣查詢,由于是基于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 //今天的氣溫
最后 在需要顯示的地方
<?php include 'weather.php' ?>
即可。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選