首頁 後端開發 php教程 php调用yahoo sina api 开发天气预报_PHP教程

php调用yahoo sina api 开发天气预报_PHP教程

Jul 20, 2016 am 11:16 AM
api php yahoo 天氣預報 開發 服務 網站 呼叫

现在的网站都会有一些服务性的东东。如日历,天气预报等等!由于google 永久性关闭了天气api  所以我又找了一个调用yahoo 和 新浪的天气预报 api。

yahoo 天气预报地址 http://developer.yahoo.com/weather/

废话不多说直接代码贴上:

 

<?php
header ( 'Content-Type: text/html; charset = utf-8' );
class weather {
	static $url = 'http://xml.weather.yahoo.com/forecastrss?u=c&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    =   "http://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.places%20where%20text='".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) { <br />       $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");
登入後複製

新浪 http://php.weather.sina.com.cn

<?php
header ( 'Content-Type: text/html; charset = utf-8' );

class weather {
	static $url = 'http://php.weather.sina.com.cn/xml.php?password=DJOYnieT8234jlsK&day=0&city=';//password是固定值
	static $city = '%B1%B1%BE%A9'; //默认城市北京
	static $weatherXML = '';
	static $file_path	=	"data/";
	/**
	  * 获得远程xml并缓存到本地
	  */
	static public function getXML($city = null) {

	  if ($city != null){<br />              $city = mb_convert_encoding ( $city, 'gbk', 'utf-8' );
			self::$city = urlencode($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;			
	   }	   
	  }
          
          $contents =   self::vget( self::$url . self::$city );	  
          
	  self::cacheXML ( $contents );
          
          self::analysisXML();
          
	}
	/**
	  * 解析xml
	  */
	static public function analysisXML() {             
            
                $XML    =   simplexml_load_file(self::$weatherXML );    
                print_r($XML);
	}
	
	/**
	  * 创建xml缓存
	  * @param $contents 要缓存的内容
	  */
	static private function cacheXML($contents) {
		$contents = str_ireplace ( '<?xml version="1.0"?>', "<?xml version=\"1.0\"?> \n", $contents );
		file_put_contents ( self::$weatherXML, $contents ) or die ( '没有写权限' );
	}
        /**
         * 模拟获取内容函数
         * @param type $url
         * @return type
         */
         
        static private function vget($url) { <br />       $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();
登入後複製

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440125.htmlTechArticle现在的网站都会有一些服务性的东东。如日历,天气预报等等!由于google 永久性关闭了天气api 所以我又找了一个调用yahoo 和 新浪的天气预...
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP與Python:了解差異 PHP與Python:了解差異 Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

PHP和Python:代碼示例和比較 PHP和Python:代碼示例和比較 Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP和Python:解釋了不同的範例 PHP和Python:解釋了不同的範例 Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

See all articles