PHP 實現擷取指定地區的天氣的方法

來源:互聯網
上載者:User
這篇文章主要介紹了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' ?>

即可。

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.