這篇文章主要介紹了PHP 擷取指定地區的天氣執行個體代碼的相關資料,需要的朋友可以參考下
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' ?>
即可。
以上就是本文的全部內容,希望對大家的學習有所協助。