search
HomeBackend DevelopmentPHP Tutorial PHP利用天候API获取天气信息

PHP利用天气API获取天气信息

??? 中国天气网提供了一些查询天气的API,访问时返回天气信息的JSON格式数据,解析就可以得到天气信息:

http://www.weather.com.cn/data/sk/101281601.html
http://www.weather.com.cn/data/cityinfo/101281601.html
http://m.weather.com.cn/data/101281601.html

后面一串数字为城市代码。

?返回的utf-8字符串

{"weatherinfo":{"city":"东莞","cityid":"101281601","temp":"22","WD":"东风","WS":"1级","SD":"90%","WSE":"1","time":"08:20","isRadar":"0","Radar":""}}

?所以首先要将城市名转换为城市代码,最简单的办法是通过读取一个文本文件来获取:

格式如:

101010100=北京 
101010200=海淀
101010300=朝阳
101010400=顺义
101010500=怀柔
101010600=通州
101010700=昌平
101010800=延庆
101010900=丰台
101011000=石景山
101011100=大兴

?

文本文件和PHP文件放在同一目录下;
于是PHP代码:

	
		<meta http-equiv="content-type" content="text/html; charset=utf-8">
		<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
		<script src="http://libs.baidu.com/bootstrap/2.0.4/js/bootstrap.min.js"></script>
		<link href="http://libs.baidu.com/bootstrap/2.0.4/css/bootstrap.min.css" rel="stylesheet">
		<title>天气查询简单版</title>
	
	
		
Weather

警告!

发生错误了亲,您输入的城市好像没有找到哦!
"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; ?>
实时天气信息
城市: ".$info["city"]."
城市ID: ".$info["cityid"]."
气温: ".$info["temp"]."℃
风向: ".$info["WD"]."
风力: ".$info["WS"]."
湿度: ".$info["SD"]."
更新时间: ".$info["time"]."
?运行结果:


方法二:
1.可以不用文件,而是从天气网服务器动态获取城市名和ID:
当访问这个地址
http://m.weather.com.cn/data5/city.xml?
服务器就会返还以下代码:
01|北京,02|上海,03|天津,04|重庆,05|黑龙江,06|吉林,07|辽宁,08|内蒙古,09|河北,10|山西,11|陕西,12|山东,13|新疆,14|西藏,15|青海,16|甘肃,17|宁夏,18|河南,19|江苏,20|湖北,21|浙江,22|安徽,23|福建,24|江西,25|湖南,26|贵州,27|四川,28|广东,29|云南,30|广西,31|海南,32|香港,33|澳门,34|台湾
2.?这时,我们就知道了省份的代码;城市的代码是在省份的基础上扩展的,知道省份代码是第一步;同时我们也知道了省份名,这样,做下拉框让用户选地区也很简单:
知道了省份我们要看这个省有些什么市,就需要依据省份代码来获取不同的文件了,例如云南是05,我们要获取云南所有州市的信息就要访问:
http://m.weather.com.cn/data5/city29.xml?
返回文本:
2901|昆明,2902|大理,2903|红河,2904|曲靖,2905|保山,2906|文山,2907|玉溪,2908|楚雄,2909|普洱,2910|昭通,2911|临沧,2912|怒江,2913|迪庆,2914|丽江,2915|德宏,2916|西双版纳
?3.但是,这样还不够,我们还需要继续缩小范围,比如我们要知道大理州有哪些县级市和县,就需要继续访问:
?http://m.weather.com.cn/data5/city2902.xml
果然,返回结果:
290201|大理,290202|云龙,290203|漾濞,290204|永平,290205|宾川,290206|弥渡,290207|祥云,290208|巍山,290209|剑川,290210|洱源,290211|鹤庆,290212|南涧
?4.这时虽然可以找到所有城市名,但这个代码还不是最终的城市代码,所以还要再来一次,不如说要找宾川的代码:
?http://m.weather.com.cn/data5/city290205.xml
?
290205|101290205
?至此,读了四次,城市名和城市代码已获取到。
当然,解析数据也可以用Javascript来完成,但是由于Ajax不支持跨域名访问,所以将数据从中国天气网的服务器上获取到本地还需要一个简单服务器脚本来做代理,它的功能只是完成将请求的文件以字符串返还Javascript来做动态数据显示,所以:
首先要写一个读取字符串的php
getstr.php
<?php echo file_get_contents($_GET['url']);
?>
?一个使用Ajax的js文件:
ajax.js
function Ajax(recvType) {
  var aj = new Object();
  aj.recvType = recvType ? recvType.toUpperCase() : 'HTML'//HTML XML
  aj.targetUrl = '';
  aj.sendString = '';
  aj.resultHandle = null;

  aj.createXMLHttpRequest = function() {
    var request = false;
    //window对象中有XMLHttpRequest存在就是非IE,包括(IE7,IE8)
    if (window.XMLHttpRequest) {
      request = new XMLHttpRequest();
      if (request.overrideMimeType) {
        request.overrideMimeType("text/xml");
      }
      //window对象中有ActiveXObject属性存在就是IE
    } else if (window.ActiveXObject) {
      var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
      for (var i = 0; i 
?网页部分代码:
<div class="iteye-blog-content-contain" style="font-size: 14px;">
<pre name="code" class="html">

  
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <script src="http://libs.baidu.com/bootstrap/2.0.4/js/bootstrap.min.js"></script>
    <link href="http://libs.baidu.com/bootstrap/2.0.4/css/bootstrap.min.css" rel="stylesheet">
    <title>实时气温信息</title>
    <script type="text/javascript" src="./ajax.js"></script>
    <script type="text/javascript">
      function str2Array(data) {
        data = data.replace(/\|/g, "\":\"");
        data = data.replace(/,/g, "\",\"");
        data = '({\"' + data + '\"})';
        return eval(data);
      }

      function getProvince() {
        var ajax = Ajax();
        ajax.get("getstr.php?url=http://m.weather.com.cn/data5/city.xml", function(data) {
          var arr = str2Array(data);
          var prov = document.getElementById("province");
          for (var p in arr) {
            prov.options.add(new Option(arr[p], p));
          }
          prov.options.selectedIndex = 0;
          getCity(prov.value);
        });
      }

      function getCity(provId) {
        var ajax = Ajax();
        ajax.get("getstr.php?url=http://m.weather.com.cn/data5/city" + provId + ".xml", function(data) {
          var arr = str2Array(data);
          var city = document.getElementById("city");
          for (var i = city.options.length; i >= 0; i--) {
            city.remove(i);
          }
          for (var p in arr) {
            city.options.add(new Option(arr[p], p));
          }
          getTown(city.value);
        });
      }

      function getTown(provId) {
        var ajax = Ajax();
        ajax.get("getstr.php?url=http://m.weather.com.cn/data5/city" + provId + ".xml", function(data) {
          var arr = str2Array(data);
          var town = document.getElementById("town");
          for (var i = town.options.length; i >= 0; i--) {
            town.remove(i);
          }
          for (var p in arr) {
            town.options.add(new Option(arr[p], p));
          }
          getCityId();
        });
      }

      function getCityId() {
        var ajax = Ajax();
        var index = document.getElementById("town").value;
        ajax.get("getstr.php?url=http://m.weather.com.cn/data5/city" + index + ".xml", function(data) {
          var arr = str2Array(data);
          cityId = arr[index];
          showWeather(cityId);
        });
      }

      function insertTab(tab, cel1, cel2) {
        var newRow = tab.insertRow(tab.rows.length);
        var cell = newRow.insertCell(0);
        cell.innerHTML = cel1;
        var cell = newRow.insertCell(1);
        cell.innerHTML = cel2;
      }

      function showWeather(cityId) {
        if (cityId == null) {
          return;
        }
        var ajax = Ajax();
        ajax.get("getstr.php?url=http://www.weather.com.cn/data/sk/" + cityId + ".html", function(data) {
          data = '(' + data + ')';
          var info = eval(data)["weatherinfo"];
          var tab = document.getElementById("weather");

          var len = tab.rows.length;
          while(len-- > 0){
            tab.deleteRow(len);
          }

          insertTab(tab, "城市:", info["city"]);
          insertTab(tab, "城市ID:", info["cityid"]);
          insertTab(tab, "气温:", info["temp"] + "℃");
          insertTab(tab, "风向:", info["WD"]);
          insertTab(tab, "风力:", info["WS"]);
          insertTab(tab, "湿度:", info["SD"]);
          insertTab(tab, "更新时间:", info["time"]);
        });
      }

      getProvince();
    </script>
    <style type="text/css">
        select {
            width: 100px;
        }
    </style>
  
  
    <div style="margin: 20px">
      <legend>
        Weather
      </legend>
      <br>
      <select id="province" onchange="getCity(this.value)"></select>
      <select id="city" onchange="getTown(this.value)"></select>
      <select id="town" onchange="getCityId()"></select>
      <br>
      <table id="weather" class="table table-striped table-bordered" style="width: 310px"></table>
    </div>
  
?运行结果:

这样做下拉框中的数据可以动态从天气网的服务器中读取过来再动态加载,因此也不用自己做转换了。
?
如果是有图片元素的数据,直接找到图片的链接,将图片链过来就可以了。


?完。
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 can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function