php免費調用天氣,php獲取天氣

本文目錄一覽:

php的socket調用可以實現查天氣嗎

本文分享下,php調用yahoo與sina的天氣api,實現實時顯示天氣預報的代碼,有興趣的朋友研究下吧。

yahoo 天氣預報

地址

代碼:

複製代碼代碼示例:

?php

header ( ‘Content-Type: text/html; charset = utf-8’ );

class weather {

static $url = ‘;w=’;

static $city = ‘Beijing’; //默認城市北京 這裡要注意的是 city 要填拼音 我試過用中文有好幾個地區都調用不到

static $weatherXML = ”;

static $woeid_file = “woeid”;

static $file_path = “data/”;

/**

* 獲得遠程xml並緩存到本地

*/

static public function getXML($city = null) {

if ($city != null){

self::$city = $city;

}

self::$weatherXML = self::$file_path . md5(self::$city) . ‘-weather.xml’;

if (file_exists( self::$weatherXML )) {

$fileTime = filemtime ( self::$weatherXML );

$stater = time () – $fileTime – 60 * 60 * 2;

if ($stater 0) {

return true;

}

}

//獲取woeid

$woeid = self::getWOEID();

self::$url = self::$url . $woeid[0];

//獲取當天 天氣

$XML = self::vget(self::$url);

//保存當天 天氣到文件

self::cacheXML($XML);

self::analysisXML($XML);

}

static public function analysisXML($simple) {

$p = xml_parser_create();

xml_parse_into_struct($p, $simple, $vals, $index);

xml_parser_free($p);

//本周天氣

$weekindex = $index[‘YWEATHER:FORECAST’];

$week = array();

foreach($weekindex as $k=$v){

$week[$k] = $vals[$v][‘attributes’];

}

unset($index);

unset($vals);

print_r($week);

/*

yweather:forecast day=”Wed” date=”18 Sep 2013″ low=”20″ high=”32″ text=”Sunny” code=”32″/

* day 星期

* date 日期

* low 最低溫度

* high 最高溫度

* test 天氣狀態

* code 天氣圖標

*/

}

/*

* 取得地區WOEID碼

*/

static private function getWOEID(){

static $woeid = array();

if(isset($woeid[self::$city])){

return $woeid[self::$city];

}

if (file_exists( self::$file_path . self::$woeid_file )) {

$woeidSTR = file_get_contents(self::$file_path . self::$woeid_file);

$woeid = json_decode($woeidSTR , true);

if(isset($woeid[self::$city])){

return $woeid[self::$city];

}

}

$geoPlaces = “‘”.self::$city.”%20CH'”;

$XML = simplexml_load_file( $geoPlaces );

if(isset($XML-results-place[0])){

$rs = $woeid[self::$city] = $XML-results-place[0]-woeid;

//保存到文件

$woeidSTR = json_encode($woeid);

file_put_contents(self::$file_path . self::$woeid_file, $woeidSTR);

return $rs;

}else{

//如果找不到城市 woeid 默認城市就改為 北京

self::$city = “Beijing”;

return self::getWOEID();

}

}

/**

* 創建xml緩存

* @param $contents 要緩存的內容

*/

static private function cacheXML($contents) {

$contents = str_ireplace ( ‘?xml version=”1.0″?’, “?xml version=\”1.0\”? \n”, $contents );

$contents = mb_convert_encoding ( $contents, ‘utf-8’, ‘gbk’ );

file_put_contents ( self::$weatherXML, $contents ) or die ( ‘沒有寫權限’ );

}

/**

* 模擬獲取內容函數

* @param type $url

* @return type

*/

static private function vget($url) {

$user_agent = “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)”;

$curl = curl_init (); // 啟動一個CURL會話

curl_setopt ( $curl, CURLOPT_URL, $url ); // 要訪問的地址

curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); // 對認證證書來源的檢查

curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 1 ); // 從證書中檢查SSL加密算法是否存在

curl_setopt ( $curl, CURLOPT_USERAGENT, $user_agent ); // 模擬用戶使用的瀏覽器

@curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 ); // 使用自動跳轉

curl_setopt ( $curl, CURLOPT_AUTOREFERER, 1 ); // 自動設置Referer

curl_setopt ( $curl, CURLOPT_HTTPGET, 1 ); // 發送一個常規的Post請求

curl_setopt ( $curl, CURLOPT_TIMEOUT, 120 ); // 設置超時限制防止死循環

curl_setopt ( $curl, CURLOPT_HEADER, 0 ); // 顯示返回的Header區域內容

curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 獲取的信息以文件流的形式返回

$tmpInfo = curl_exec ( $curl ); // 執行操作

if (curl_errno ( $curl )) {

curl_close ( $curl ); // 關閉CURL會話

die(‘Errno’ . curl_error ( $curl )) ;

}

curl_close ( $curl ); // 關閉CURL會話

return $tmpInfo; // 返回數據

}

}

weather::getXML(“Changsha”);

PHP調用2345天氣問題

$var是一個數組,weatherid是數組中的一個元素。在此之前,一般會先給$var中的每一個元素賦值,例如:$var[‘weatherid’] = 300,那麼整個URL其實就是:

如何使用PHP調用API接口實現天氣查詢功能

最近在做微信公眾平台測試時,想在裏面子菜單上添加查詢未來幾天(包括今天)天氣的功能,就查找了下好用的天氣預報查詢接口API,使用比較多的有:國家氣象局天氣接口、新浪天氣預報接口、百度天氣預報接口、google天氣接口、Yahoo天氣接口等等,我使用的是百度提供的免費天氣查詢接口API,下面與大家分享下…

1、查詢方式:

百度提供的是根據緯度和城市名查詢天氣情況

2、接口事例:

3、接口參數說明:

4、返回結果說明:

5、

//城市名

$city = ‘上海’;

//對json格式的字符串進行編碼

$arr =json_decode($str,TRUE);

print_r($atr);

//城市名

   $city = ‘上海’;

 

   //獲取json格式的數據

   $str =file_get_contents(“”.$city.”output=jsonak=5slgyqGDENN7Sy7pw29IUvrZ”);

   //對json格式的字符串進行編碼

   $arr =json_decode($str,TRUE);      

   print_r($atr);

6、返回頁面的是json編碼後的數據:

[plain] view plain copy print?

meta charset=”UTF-8″

Array

(

[error] = 0

[status] = success

[date] = 2014-03-17

[results] = Array

(

[0] = Array

(

[currentCity]= 上海

[weather_data]= Array

(

[0]= Array

(

[date] = 周一(今天, 實時:19℃)

[dayPictureUrl] =

[nightPictureUrl] =

[weather] = 晴

[wind] = 西南風3-4級

[temperature] = 13℃

)

[1] = Array

(

[date]= 周二

[dayPictureUrl] =

[nightPictureUrl] = 

[weather]= 多雲轉陰

[wind]= 東北風3-4級

[temperature] = 24 ~ 9℃

)

[2] = Array

(

[date]= 周三

[dayPictureUrl] =

[nightPictureUrl] = 

[weather]= 中雨轉小雨

[wind]= 東北風3-4級

[temperature] = 15 ~ 8℃

)

[3] = Array

(

[date]= 周四

[dayPictureUrl] =

[nightPictureUrl] =

[weather]= 多雲轉晴

[wind]= 北風3-4級

[temperature] = 14 ~ 6℃

)

)

)

)

)

meta charset=”UTF-8″

Array

(

   [error] = 0

   [status] = success

   [date] = 2014-03-17

   [results] = Array

       (

           [0] = Array

               (

                   [currentCity]= 上海

                   [weather_data]= Array

                       (

                           [0]= Array

                               (

                                  [date] = 周一(今天, 實時:19℃)

                                  [dayPictureUrl] =

                                  [nightPictureUrl] =

                                   [weather] = 晴

                                  [wind] = 西南風3-4級

                                  [temperature] = 13℃

                               )

                           [1] = Array

                               (

                                   [date]= 周二

                                  [dayPictureUrl] =

                                  [nightPictureUrl] =

                                   [weather]= 多雲轉陰

                                   [wind]= 東北風3-4級

                                  [temperature] = 24 ~ 9℃

                               )

                           [2] = Array

                               (

                                   [date]= 周三

                                  [dayPictureUrl] =

                                  [nightPictureUrl] =

                                   [weather]= 中雨轉小雨

                                   [wind]= 東北風3-4級

                                  [temperature] = 15 ~ 8℃

                               )

                           [3] = Array

                               (

                                   [date]= 周四

                                  [dayPictureUrl] =

                                   [nightPictureUrl] =

                                   [weather]= 多雲轉晴

                                   [wind]= 北風3-4級

                                  [temperature] = 14 ~ 6℃

                               )

                       )

               )

       )

)

7、PHP中自帶了處理json格式字符串的內置函數,下面做一個事例,並給出完整代碼:

[php] view plain copy print?

metacharset=”UTF-8″

?php

//城市名

$city = ‘上海’;

//獲取json格式的數據

$str = file_get_contents(“”.$city.”output=jsonak=5slgyqGDENN7Sy7pw29IUvrZ”);

//對json格式的字符串進行編碼

$arr = json_decode($str,TRUE);

echo “城市:”.$arr[‘results’][0][‘currentCity’].” 日期:”.$arr[‘date’].”br /br /”;

foreach($arr[‘results’][0][‘weather_data’]as $val)

{

echo $val[‘date’].”br/”;

echo “天氣:{$val[‘weather’]}br/”;

echo “風向:{$val[‘wind’]}br/”;

echo “溫度:{$val[‘temperature’]}br/br /”;

}

?

metacharset=”UTF-8″

?php

   //城市名

   $city = ‘上海’;

 

   //獲取json格式的數據

   $str = file_get_contents(“”.$city.”output=jsonak=5slgyqGDENN7Sy7pw29IUvrZ”);

   //對json格式的字符串進行編碼

   $arr = json_decode($str,TRUE);      

   echo “城市:”.$arr[‘results’][0][‘currentCity’].” 日期:”.$arr[‘date’].”br /br /”;

   foreach($arr[‘results’][0][‘weather_data’]as $val)

   {

       echo $val[‘date’].”br/”;

       echo “天氣:{$val[‘weather’]}br/”;

       echo “風向:{$val[‘wind’]}br/”;

       echo “溫度:{$val[‘temperature’]}br/br /”;

   }

?

8、返回的內容如下:

PHP 頁面調用天氣預報web服務 我想在一個PHP頁面直接調用現成的webservice

完全可以。前提是要打開soap擴展,調用方法如下:

?php

$client = new SoapClient(”);

$parm=array(‘theCityCode’=’三亞’,’theUserID’=”);

$result=$client-getWeather($parm);

print_r($result);

?

php獲取天氣預報的代碼

?php    

$URLStyle = “”;    

$chinaURL = sprintf($URLStyle, “china”);    

$chinaStr = file_get_contents($chinaURL);    

$chinaObj = simplexml_load_string($chinaStr);    

$chinaObjLen = count($chinaObj-city);    

echo “chinaObjLen = “.$chinaObjLen.”\n”;    

for ($i=0;$i$chinaObjLen;$i++){    

//遍歷省一級節點,共37個    

        $level1 = $chinaObj-city[$i][“pyName”];    

        $shengjiURL = sprintf($URLStyle, $level1);    

        $shengjiStr = file_get_contents($shengjiURL);    

        //echo $shengjiStr;    

        $shengjiObj = simplexml_load_string($shengjiStr);     

        $shengjiObjLen = count($shengjiObj-city);    

//      echo $chinaObj-city[$i][“quName”];    

//      echo ” “.$shengjiObjLen.”\n”;    

        for ($j=0;$j$shengjiObjLen;$j++){    

        //遍歷市一級節點    

                $level2 = $shengjiObj-city[$j][“pyName”];    

                $shijiURL = sprintf($URLStyle, $level2);    

                $shijiStr = file_get_contents($shijiURL);    

                //echo $shijiStr;    

                $shijiObj = simplexml_load_string($shijiStr);     

             //直轄市和海南、台灣、釣魚島等沒有縣級節點    

                if(!$shijiObj){    

                        echo “WARNNING: not exsit next level node. – “.$level1.”-“.$shijiURL.”\n”;    

                        echo ‘  “‘.$shengjiObj-city[$j][“cityname”].'” = ‘;    

                        echo $shengjiObj-city[$j][“url”].”,\n”;    

                        continue;    

                }    

                $shijiObjLen = count($shijiObj-city);    

                //echo $shengjiObj-city[$j][“cityname”].”  “;    

                //echo $shijiObjLen.”\n”;    

                for ($k=0;$k$shijiObjLen;$k++){    

                //遍歷縣一級節點    

                        $xianji_code = $shijiObj-city[$k][“url”];    

                        echo ‘  “‘.$shijiObj-city[$k][“cityname”].'” = ‘;    

                        echo $shijiObj-city[$k][“url”].”,\n”;    

                        //echo $xianji_code.”\n”;     

                }    

        }    

}           

//print_r($chinaObj);    

?

通過XML接口根節點遞歸獲得全國幾千個縣以上城市cide code的代碼

php怎麼抓取天氣預報?

可以藉由php的api或者preg_match_all偷偷擷取去達成目的

這裡給你一段我給台灣朋友有一段源碼

?php

header(\”Content-Type: text/html; charset=utf-8\”);

function getWeather($city){

$toURL = \”

$city.htm\”;

$post = array();

$ch = curl_init();

$options = array(

CURLOPT_REFERER=”,

CURLOPT_URL=$toURL,

CURLOPT_VERBOSE=0,

CURLOPT_RETURNTRANSFER=true,

CURLOPT_USERAGENT=\”Mozilla/4.0 (compatible;)\”,

CURLOPT_POST=true,

CURLOPT_POSTFIELDS=http_build_query($post),

);

curl_setopt_array($ch, $options);

$result = curl_exec($ch); 

curl_close($ch);

//連接中央氣象局

echo ‘pre’;

preg_match_all(‘/table class=\”FcstBoxTable01\” [^]*[^]*(.*)\/div/si’,$result, $matches, PREG_SET_ORDER);

preg_match_all(‘/td nowrap=\”nowrap\” [^]*[^]*(.*)\/td/si’,$matches[0][1], $m1, PREG_SET_ORDER);

$m2 = explode(‘/td’,$m1[0][1]);

// print_r($m2);//取得每日資料m2[0~6]

$weather = array();

for($i=0;$i=6;$i++){

preg_match_all(‘/src=[^]*[^](.*)/si’,$m2[$i], $m5, PREG_SET_ORDER);//取得天氣圖檔

$m6 = explode(‘\”‘,$m5[0][0]);

$wi=’

($m6[1],’\.\./\.\./’);

$wtitle = $m6[3];

     print_r($wtitle);

$weather[$i][‘date’] = date(\”m-d\”, mktime(0, 0, 0, date(\”m\”), date(\”d\”)+$i,date(\”Y\”)));

$weather[$i][‘temperature’] = trim(strip_tags($m2[$i]));

$weather[$i][‘title’] = $wtitle;

$weather[$i][‘img’] = $wi;

}

return($weather);

}

  $weather=getWeather(\”Taipei_City\”) ;   

  print_r($weather);

  

// header(\”Location:loc.php\”);

?

首先

$toURL = \”\”;

這裡是讀取資料的網址

上面的是台灣中央氣象局

preg_match_all(‘/table class=\”FcstBoxTable01\” [^]*[^]*(.*)\/div/si’,$result, $matches, PREG_SET_ORDER);

preg_match_all(‘/td nowrap=\”nowrap\” [^]*[^]*(.*)\/td/si’,$matches[0][1], $m1, PREG_SET_ORDER);

這裡是截取台灣中央氣象局網頁信息table class=\”FcstBoxTable01\” [^]*[^]*(.*)\/div的資料以及td nowrap=\”nowrap\” [^]*[^]*(.*)\/td的資料分別是1天跟1周

$m2 = explode(‘/td’,$m1[0][1]);

// print_r($m2);//取得每日資料m2[0~6]

這裡是取得每日的資料

preg_match_all(‘/src=[^]*[^](.*)/si’,$m2[$i], $m5, PREG_SET_ORDER);//取得天氣圖檔

這裡是取得天氣的圖檔

$m6 = explode(‘\”‘,$m5[0][0]);

$wi=’

($m6[1],’\.\./\.\./’);

$wtitle = $m6[3];

     print_r($wtitle);

$weather[$i][‘date’] = date(\”m-d\”, mktime(0, 0, 0, date(\”m\”), date(\”d\”)+$i,date(\”Y\”)));

$weather[$i][‘temperature’] = trim(strip_tags($m2[$i]));

$weather[$i][‘title’] = $wtitle;

$weather[$i][‘img’] = $wi;

這裡是返回的網址,日期,標題,圖檔等等的資料

  $weather=getWeather(\”Taipei_City\”) ;   

  print_r($weather);

然後這裡是顯示出地區的一周天氣預報

結論:就是如果你想從網站上面截取天氣預報

在php可以是用preg_match_all(網頁的表格table,表格的列數tr,表格的欄位td,或者更加廣泛的標籤div等等獲取)

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/308565.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2025-01-03 14:49
下一篇 2025-01-03 14:49

相關推薦

  • PHP和Python哪個好找工作?

    PHP和Python都是非常流行的編程語言,它們被廣泛應用於不同領域的開發中。但是,在考慮擇業方向的時候,很多人都會有一個問題:PHP和Python哪個好找工作?這篇文章將從多個方…

    編程 2025-04-29
  • 使用ActivityWeatherBinding簡化天氣應用程序的開發

    如何使用ActivityWeatherBinding加快並簡化天氣應用程序的開發?本文將從以下幾個方面進行詳細闡述。 一、簡介 ActivityWeatherBinding是一個在…

    編程 2025-04-29
  • PHP怎麼接幣

    想要在自己的網站或應用中接受比特幣等加密貨幣的支付,就需要對該加密貨幣擁有一定的了解,並使用對應的API進行開發。本文將從多個方面詳細闡述如何使用PHP接受加密貨幣的支付。 一、環…

    編程 2025-04-29
  • 使用PHP foreach遍歷有相同屬性的值

    本篇文章將介紹如何使用PHP foreach遍歷具有相同屬性的值,並給出相應的代碼示例。 一、基礎概念 在講解如何使用PHP foreach遍歷有相同屬性的值之前,我們需要先了解幾…

    編程 2025-04-28
  • PHP獲取301跳轉後的地址

    本文將為大家介紹如何使用PHP獲取301跳轉後的地址。301重定向是什麼呢?當我們訪問一個網頁A,但是它已經被遷移到了另一個地址B,此時若服務器端做了301重定向,那麼你的瀏覽器在…

    編程 2025-04-27
  • PHP登錄頁面代碼實現

    本文將從多個方面詳細闡述如何使用PHP編寫一個簡單的登錄頁面。 1. PHP登錄頁面基本架構 在PHP登錄頁面中,需要包含HTML表單,用戶在表單中輸入賬號密碼等信息,提交表單後服…

    編程 2025-04-27
  • Python實現天氣關係圖

    本文將介紹如何使用Python繪製天氣關係圖,通過分析和可視化天氣數據,幫助我們更好地了解天氣的變化和趨勢。 一、數據準備 首先我們需要從數據源中獲取天氣數據。我們可以使用爬蟲技術…

    編程 2025-04-27
  • PHP與Python的比較

    本文將會對PHP與Python進行比較和對比分析,包括語法特性、優缺點等方面。幫助讀者更好地理解和使用這兩種語言。 一、語法特性 PHP語法特性: <?php // 簡單的P…

    編程 2025-04-27
  • PHP版本管理工具phpenv詳解

    在PHP項目開發過程中,我們可能需要用到不同版本的PHP環境來試驗不同的功能或避免不同版本的兼容性問題。或者我們需要在同一台服務器上同時運行多個不同版本的PHP語言。但是每次手動安…

    編程 2025-04-24
  • PHP數組去重詳解

    一、array_unique函數 array_unique是php中常用的數組去重函數,它基於值來判斷元素是否重複,具體使用方法如下: $array = array(‘a’, ‘b…

    編程 2025-04-24

發表回復

登錄後才能評論