Home Backend Development PHP Tutorial Implementation code for php calling yahoo sina api weather forecast

Implementation code for php calling yahoo sina api weather forecast

Jul 25, 2016 am 08:56 AM

  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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles