search
HomeBackend DevelopmentPHP TutorialImplementation code for php calling yahoo sina api weather forecast

  1. header ( 'Content-Type: text/html; charset = utf-8' );
  2. class weather {
  3. static $url = 'http://xml.weather.yahoo.com /forecastrss?u=c&w=';
  4. static $city = 'Beijing'; //Default city Beijing. What should be noted here is that city requires pinyin. I have tried using Chinese and it cannot be called in several regions.
  5. static $weatherXML = '';
  6. static $woeid_file = "woeid";
  7. static $file_path = "data/";
  8. /**
  9. * Get remote xml and cache it locally
  10. */
  11. static public function getXML($city = null) {
  12. if ($city != null){
  13. self::$city = $city;
  14. }
  15. self::$weatherXML = self::$file_path . md5(self::$city) . '-weather.xml';
  16. if (file_exists ( self::$weatherXML )) {
  17. $fileTime = filemtime ( self::$weatherXML );
  18. $stater = time () - $fileTime - 60 * 60 * 2;
  19. if ($stater > 0) {
  20. return true;
  21. }
  22. }
  23. //Get woeid
  24. $woeid = self::getWOEID();
  25. self::$url = self::$url . $woeid[0];
  26. //Get the weather for the day
  27. $ XML = self::vget(self::$url);
  28. //Save the day's weather to a file
  29. self::cacheXML($XML);
  30. self::analysisXML($XML);
  31. }
  32. static public function analysisXML($simple) {
  33. $p = xml_parser_create();
  34. xml_parse_into_struct($p, $simple, $vals, $index);
  35. xml_parser_free($p);
  36. //Weather this week
  37. $weekindex = $index['YWEATHER:FORECAST'];
  38. $week = array();
  39. foreach($weekindex as $k=>$v){
  40. $week[$k] = $vals[$v][' attributes'];
  41. }
  42. unset($index);
  43. unset($vals);
  44. print_r($week);
  45. /*
  46. * day week
  47. * date date
  48. * low minimum temperature
  49. * high maximum temperature
  50. * test weather status
  51. * code weather icon
  52. */
  53. }
  54. /*
  55. * Get the area WOEID code
  56. */
  57. static private function getWOEID(){
  58. static $woeid = array();
  59. if(isset($woeid[self::$city])) {
  60. return $woeid[self::$city];
  61. }
  62. if (file_exists( self::$file_path . self::$woeid_file )) {
  63. $woeidSTR = file_get_contents(self::$file_path . self:: $woeid_file);
  64. $woeid = json_decode($woeidSTR , true);
  65. if(isset($woeid[self::$city])){
  66. return $woeid[self::$city];
  67. }
  68. }
  69. $geoPlaces = "http://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.places%20where%20text='".self::$city."%20CH'" ;
  70. $XML = simplexml_load_file( $geoPlaces );
  71. if(isset($XML->results->place[0])){
  72. $rs = $woeid[self::$city] = $XML ->results->place[0]->woeid;
  73. //Save to file
  74. $woeidSTR = json_encode($woeid);
  75. file_put_contents(self::$file_path . self::$woeid_file, $woeidSTR) ;
  76. return $rs;
  77. }else{
  78. //If the city woeid cannot be found, the default city will be changed to Beijing
  79. self::$city = "Beijing";
  80. return self::getWOEID();
  81. }
  82. }
  83. /**
  84. * Create xml cache
  85. * @param $contents The content to be cached
  86. */
  87. static private function cacheXML($contents) {
  88. $contents = str_ireplace ( '', " n", $contents );
  89. $contents = mb_convert_encoding ( $contents, 'utf-8', 'gbk' );
  90. file_put_contents ( self::$weatherXML, $contents ) or die ( 'No write permission' );
  91. }
  92. /**
  93. * Simulate the function of getting content
  94. * @param type $url
  95. * @return type
  96. */
  97. static private function vget($url) {
  98. $user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
  99. $curl = curl_init (); // Start a CURL session
  100. curl_setopt ( $curl, CURLOPT_URL, $url ); // The address to be accessed
  101. curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); // Check the source of the authentication certificate
  102. curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 1 ); // Check whether the SSL encryption algorithm exists from the certificate
  103. curl_setopt ( $curl, CURLOPT_USERAGENT, $user_agent ); // Simulate the browser used by the user
  104. @curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 ); // Use automatic redirect
  105. curl_setopt ( $curl, CURLOPT_AUTOREFERER, 1 ); // Automatically set the Referer
  106. curl_setopt ( $curl, CURLOPT_HTTPGET, 1 ); // Send a regular Post request
  107. curl_setopt ( $curl, CURLOPT_TIMEOUT , 120 ); // Set timeout limit to prevent endless loops
  108. curl_setopt ( $curl, CURLOPT_HEADER, 0 ); // Display the content of the returned Header area
  109. curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // The information obtained is in the file stream Return in the form of
  110. $tmpInfo = curl_exec ( $curl ); // Perform the operation
  111. if (curl_errno ( $curl )) {
  112. curl_close ( $curl ); // Close the CURL session
  113. die('Errno' . curl_error ( $curl )) ;
  114. }
  115. curl_close ( $curl ); // Close CURL session
  116. return $tmpInfo; // Return data
  117. }
  118. }
  119. weather::getXML("Changsha");
Copy code

2,新浪天气 地址:http://php.weather.sina.com.cn 代码:

  1. header ( 'Content-Type: text/html; charset = utf-8' );
  2. class weather {
  3. static $url = 'http://php.weather.sina.com.cn/xml.php?password=DJOYnieT8234jlsK&day=0&city=';//password是固定值
  4. static $city = '%B1%B1%BE%A9'; //默认城市北京
  5. static $weatherXML = '';
  6. static $file_path = "data/";
  7. /**
  8. * Get remote xml and cache it locally
  9. */
  10. static public function getXML($city = null) {
  11. if ($city != null){
  12. $city = mb_convert_encoding ( $city, 'gbk', 'utf-8' );
  13. self::$city = urlencode($city);
  14. }
  15. self::$weatherXML = self::$file_path . md5(self::$city) . '-weather.xml';
  16. if (file_exists( self::$weatherXML )) {
  17. $fileTime = filemtime ( self::$weatherXML );
  18. $stater = time () - $fileTime - 60 * 60 * 2;
  19. if ($stater > 0) {
  20. return true;
  21. }
  22. }
  23. $contents = self::vget( self::$url . self::$city );
  24. self::cacheXML ( $contents );
  25. self::analysisXML();
  26. }
  27. /**
  28. * Parse xml
  29. */
  30. static public function analysisXML() {
  31. $XML = simplexml_load_file(self::$weatherXML );
  32. print_r($XML);
  33. }
  34. /**
  35. * Create xml cache
  36. * @param $contents The content to be cached
  37. */
  38. static private function cacheXML($contents) {
  39. $contents = str_ireplace ( '', " n", $contents );
  40. file_put_contents ( self::$weatherXML, $contents ) or die ( '没有写权限' );
  41. }
  42. /**
  43. * Simulate the function of getting content
  44. * @param type $url
  45. * @return type
  46. */
  47. static private function vget($url) {
  48. $user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
  49. $curl = curl_init (); // 启动一个CURL会话
  50. curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
  51. curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); // 对认证证书来源的检查
  52. curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 1 ); // 从证书中检查SSL加密算法是否存在
  53. curl_setopt ( $curl, CURLOPT_USERAGENT, $user_agent ); // 模拟用户使用的浏览器
  54. @curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 ); // 使用自动跳转
  55. curl_setopt ( $curl, CURLOPT_AUTOREFERER, 1 ); // 自动设置Referer
  56. curl_setopt ( $curl, CURLOPT_HTTPGET, 1 ); // 发送一个常规的Post请求
  57. curl_setopt ( $curl, CURLOPT_TIMEOUT, 120 ); // 设置超时限制防止死循环
  58. curl_setopt ( $curl, CURLOPT_HEADER, 0 ); // 显示返回的Header区域内容
  59. curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
  60. $tmpInfo = curl_exec ( $curl ); // 执行操作
  61. if (curl_errno ( $curl )) {
  62. curl_close ( $curl ); // 关闭CURL会话
  63. die('Errno' . curl_error ( $curl )) ;
  64. }
  65. curl_close ( $curl ); // 关闭CURL会话
  66. return $tmpInfo; // 返回数据
  67. }
  68. }
  69. weather::getXML();
复制代码


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version