亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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獲取天氣信息

??? 中國天氣網(wǎng)提供了一些查詢天氣的API,訪問時(shí)返回天氣信息的JSON格式數(shù)據(jù),解析就可以得到天氣信息:

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

后面一串?dāng)?shù)字為城市代碼。

?返回的utf-8字符串

{"weatherinfo":{"city":"東莞","cityid":"101281601","temp":"22","WD":"東風(fēng)","WS":"1級","SD":"90%","WSE":"1","time":"08:20","isRadar":"0","Radar":""}}

?所以首先要將城市名轉(zhuǎn)換為城市代碼,最簡單的辦法是通過讀取一個(gè)文本文件來獲?。?/p>

格式如:

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

警告!

發(fā)生錯(cuò)誤了親,您輸入的城市好像沒有找到哦!
"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; ?>
實(shí)時(shí)天氣信息
城市: ".$info["city"]."
城市ID: ".$info["cityid"]."
氣溫: ".$info["temp"]."℃
風(fēng)向: ".$info["WD"]."
風(fēng)力: ".$info["WS"]."
濕度: ".$info["SD"]."
更新時(shí)間: ".$info["time"]."
?運(yùn)行結(jié)果:


方法二:
1.可以不用文件,而是從天氣網(wǎng)服務(wù)器動態(tài)獲取城市名和ID:
當(dāng)訪問這個(gè)地址
http://m.weather.com.cn/data5/city.xml?
服務(wù)器就會返還以下代碼:
01|北京,02|上海,03|天津,04|重慶,05|黑龍江,06|吉林,07|遼寧,08|內(nèi)蒙古,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.?這時(shí),我們就知道了省份的代碼;城市的代碼是在省份的基礎(chǔ)上擴(kuò)展的,知道省份代碼是第一步;同時(shí)我們也知道了省份名,這樣,做下拉框讓用戶選地區(qū)也很簡單:
知道了省份我們要看這個(gè)省有些什么市,就需要依據(jù)省份代碼來獲取不同的文件了,例如云南是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.但是,這樣還不夠,我們還需要繼續(xù)縮小范圍,比如我們要知道大理州有哪些縣級市和縣,就需要繼續(xù)訪問:
?http://m.weather.com.cn/data5/city2902.xml
果然,返回結(jié)果:
290201|大理,290202|云龍,290203|漾濞,290204|永平,290205|賓川,290206|彌渡,290207|祥云,290208|巍山,290209|劍川,290210|洱源,290211|鶴慶,290212|南澗
?4.這時(shí)雖然可以找到所有城市名,但這個(gè)代碼還不是最終的城市代碼,所以還要再來一次,不如說要找賓川的代碼:
?http://m.weather.com.cn/data5/city290205.xml
?
290205|101290205
?至此,讀了四次,城市名和城市代碼已獲取到。
當(dāng)然,解析數(shù)據(jù)也可以用Javascript來完成,但是由于Ajax不支持跨域名訪問,所以將數(shù)據(jù)從中國天氣網(wǎng)的服務(wù)器上獲取到本地還需要一個(gè)簡單服務(wù)器腳本來做代理,它的功能只是完成將請求的文件以字符串返還Javascript來做動態(tài)數(shù)據(jù)顯示,所以:
首先要寫一個(gè)讀取字符串的php
getstr.php
<?php echo file_get_contents($_GET['url']);
?>
?一個(gè)使用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 
?網(wǎng)頁部分代碼:
<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>實(shí)時(shí)氣溫信息</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, "風(fēng)向:", info["WD"]);
          insertTab(tab, "風(fēng)力:", info["WS"]);
          insertTab(tab, "濕度:", info["SD"]);
          insertTab(tab, "更新時(shí)間:", 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>
  
?運(yùn)行結(jié)果:

這樣做下拉框中的數(shù)據(jù)可以動態(tài)從天氣網(wǎng)的服務(wù)器中讀取過來再動態(tài)加載,因此也不用自己做轉(zhuǎn)換了。
?
如果是有圖片元素的數(shù)據(jù),直接找到圖片的鏈接,將圖片鏈過來就可以了。


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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1502
276
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提交表單通過后,彈出的對話框怎樣在當(dāng)前頁彈出,該如何解決 php提交表單通過后,彈出的對話框怎樣在當(dāng)前頁彈出,該如何解決 Jun 13, 2016 am 10:23 AM

php提交表單通過后,彈出的對話框怎樣在當(dāng)前頁彈出php提交表單通過后,彈出的對話框怎樣在當(dāng)前頁彈出而不是在空白頁彈出?想實(shí)現(xiàn)這樣的效果:而不是空白頁彈出:------解決方案--------------------如果你的驗(yàn)證用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.

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

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 are the differences between xdata and data What are the differences between xdata and data Dec 11, 2023 am 11:30 AM

The differences are: 1. xdata usually refers to independent variables, while data refers to the entire data set; 2. xdata is mainly used to establish data analysis models, while data is used for data analysis and statistics; 3. xdata is usually used for regression Analysis, variance analysis, predictive modeling, data can be analyzed using various statistical methods; 4. xdata usually requires data preprocessing, and data can contain complete original data.

See all articles