在開發網站的時候用到天氣查詢,由于是基于Wordpress的 所以有很多限制,先建一個【weather.PHP】的文件,然后看代碼:
1
2
3
4
5
6
7
8
|
<?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; |
對于:
1
2
3
|
$url = 'http://m.weather.com.cn/data/' ; $id = '101181101' ; //焦作的代號 $data = file_get_contents ( $url . $id . '.html' ); |
可簡寫為:
1
|
$data = file_get_contents ( 'http://m.weather.com.cn/data/101181101.html' ); |
而對于:
1
|
$obj =json_decode( $data ); |
它是把獲取的json數據轉化為一個對象,方便調用;
那么最后一句:
1
|
echo $obj ->weatherinfo->city. ':' . $obj ->weatherinfo->weather1. ' ' . $obj ->weatherinfo->temp1; |
就是獲取指定的數據并按照一定格式輸出,
1
2
3
|
$obj ->weatherinfo->city //城市 $obj ->weatherinfo->weather1 //今天的天氣 $obj ->weatherinfo->temp1 //今天的氣溫 |
最后 在需要顯示的地方
1
|
<?php include 'weather.php' ?> |
即可。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!