Table of Contents
警告!
Home Backend Development PHP Tutorial PHP利用天候API获取天气信息

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

Jun 13, 2016 pm 12:48 PM
data gt lt weather

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":""}}
Copy after login

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

格式如:

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

?

文本文件和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>
	
	
		
Copy after login
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|台湾
Copy after login
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|西双版纳
Copy after login
?3.但是,这样还不够,我们还需要继续缩小范围,比如我们要知道大理州有哪些县级市和县,就需要继续访问:
?http://m.weather.com.cn/data5/city2902.xml
果然,返回结果:
290201|大理,290202|云龙,290203|漾濞,290204|永平,290205|宾川,290206|弥渡,290207|祥云,290208|巍山,290209|剑川,290210|洱源,290211|鹤庆,290212|南涧
Copy after login
?4.这时虽然可以找到所有城市名,但这个代码还不是最终的城市代码,所以还要再来一次,不如说要找宾川的代码:
?http://m.weather.com.cn/data5/city290205.xml
?
290205|101290205
Copy after login
?至此,读了四次,城市名和城市代码已获取到。
当然,解析数据也可以用Javascript来完成,但是由于Ajax不支持跨域名访问,所以将数据从中国天气网的服务器上获取到本地还需要一个简单服务器脚本来做代理,它的功能只是完成将请求的文件以字符串返还Javascript来做动态数据显示,所以:
首先要写一个读取字符串的php
getstr.php
<?php echo file_get_contents($_GET['url']);
?>
Copy after login
?一个使用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>
  
Copy after login
?运行结果:

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


?完。
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 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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

What data is in the data folder? What data is in the data folder? May 05, 2023 pm 04:30 PM

The data folder contains system and program data, such as software settings and installation packages. Each folder in the Data folder represents a different type of data storage folder, regardless of whether the Data file refers to the file name Data or the extension. Named data, they are all data files customized by the system or program. Data is a backup file for data storage. Generally, it can be opened with meidaplayer, notepad or word.

Is watch4pro better or gt? Is watch4pro better or gt? Sep 26, 2023 pm 02:45 PM

Watch4pro and gt each have different features and applicable scenarios. If you focus on comprehensive functions, high performance and stylish appearance, and are willing to bear a higher price, then Watch 4 Pro may be more suitable. If you don’t have high functional requirements and pay more attention to battery life and reasonable price, then the GT series may be more suitable. The final choice should be decided based on personal needs, budget and preferences. It is recommended to carefully consider your own needs before purchasing and refer to the reviews and comparisons of various products to make a more informed choice.

What to do if mysql load data is garbled? What to do if mysql load data is garbled? Feb 16, 2023 am 10:37 AM

The solution to the garbled mysql load data: 1. Find the SQL statement with garbled characters; 2. Modify the statement to "LOAD DATA LOCAL INFILE "employee.txt" INTO TABLE EMPLOYEE character set utf8;".

How to optimize iPad battery life with iPadOS 17.4 How to optimize iPad battery life with iPadOS 17.4 Mar 21, 2024 pm 10:31 PM

How to Optimize iPad Battery Life with iPadOS 17.4 Extending battery life is key to the mobile device experience, and the iPad is a good example. If you feel like your iPad's battery is draining too quickly, don't worry, there are a number of tricks and tweaks in iPadOS 17.4 that can significantly extend the run time of your device. The goal of this in-depth guide is not just to provide information, but to change the way you use your iPad, enhance your overall battery management, and ensure you can rely on your device for longer without having to charge it. By adopting the practices outlined here, you take a step toward more efficient and mindful use of technology that is tailored to your individual needs and usage patterns. Identify major energy consumers

See all articles