Home php教程 PHP源码 一个高效的根据IP自动显示天气预报的方案

一个高效的根据IP自动显示天气预报的方案

May 25, 2016 pm 05:05 PM
weather forecast plan Efficient

php代码

1

2

3

4

5

6

7

8

9

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

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

<?php

class weather{

    // 省和省会

    private $capital = array(

        &#39;黑龙江省&#39;=>&#39;哈尔滨市&#39;,

        &#39;吉林省&#39;=>&#39;长春市&#39;,

        &#39;辽宁省&#39;=>&#39;沈阳市&#39;,

        &#39;河北省&#39;=>&#39;石家庄市&#39;,

        &#39;山西省&#39;=>&#39;太原市&#39;,

        &#39;山东省&#39;=>&#39;济南市&#39;,

        &#39;青海省&#39;=>&#39;西宁市&#39;,

        &#39;甘肃省&#39;=>&#39;兰州市&#39;,

        &#39;陕西省&#39;=>&#39;西安市&#39;,

        &#39;河南省&#39;=>&#39;郑州市&#39;,

        &#39;江苏省&#39;=>&#39;南京市&#39;,

        &#39;四川省&#39;=>&#39;成都市&#39;,

        &#39;湖北省&#39;=>&#39;武汉市&#39;,

        &#39;安徽省&#39;=>&#39;合肥市&#39;,

        &#39;浙江省&#39;=>&#39;杭州市&#39;,

        &#39;湖南省&#39;=>&#39;长沙市&#39;,

        &#39;江西省&#39;=>&#39;南昌市&#39;,

        &#39;贵州省&#39;=>&#39;贵阳市&#39;,

        &#39;福建省&#39;=>&#39;福州市&#39;,

        &#39;台湾省&#39;=>&#39;台北市&#39;,

        &#39;云南省&#39;=>&#39;昆明市&#39;,

        &#39;广东省&#39;=>&#39;广州市&#39;,

        &#39;海南省&#39;=>&#39;海口市&#39;,

        &#39;上海市&#39;=>&#39;上海&#39;,

        &#39;北京市&#39;=>&#39;北京&#39;,

        &#39;天津市&#39;=>&#39;天津&#39;,

        &#39;重庆市&#39;=>&#39;重庆&#39;,

        &#39;香港&#39;=>&#39;香港&#39;,

        &#39;澳门&#39;=>&#39;澳门&#39;,

        &#39;新疆&#39;=>&#39;乌鲁木齐市&#39;,

        &#39;内蒙古&#39;=>&#39;呼和浩特市&#39;,

        &#39;宁夏&#39;=>&#39;银川市&#39;,

        &#39;西藏&#39;=>&#39;拉萨市&#39;,

        &#39;广西&#39;=>&#39;南宁市&#39;

    );

    public $province = &#39;北京&#39;;// 默认

    public $city = &#39;北京&#39;;// 默认

 

    // 获取ip

    static function getIP(){

        $ip = &#39;127.0.0.1&#39;;

        if(isset($_SERVER)){

            if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])){

                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];

            }else if(isset($_SERVER["HTTP_CLIENT_IP"])) {

                $ip = $_SERVER["HTTP_CLIENT_IP"];

            }else{

                $ip = $_SERVER["REMOTE_ADDR"];

            }

        }else{

            if(getenv("HTTP_X_FORWARDED_FOR")){

                $ip = getenv("HTTP_X_FORWARDED_FOR");

            }else if(getenv("HTTP_CLIENT_IP")) {

                $ip = getenv("HTTP_CLIENT_IP");

            }else{

                $ip = getenv("REMOTE_ADDR");

            }

        }

        return $ip;

    }

 

    public function setArea($addr){

        // 分割省市

        foreach($this->capital as $p => $c){

            if(strpos($addr,$p) === 0){

                $this->province = str_replace(array(&#39;省&#39;,&#39;市&#39;),&#39;&#39;,$p);

                $this->city = substr($addr,strlen($p));

                if($this->city == &#39;&#39;){

                    $this->city = $c;// 默认省会

                }

            }

        }

    }

    public function getAreaCode(){

        $code = &#39;101010100&#39;;// 默认北京

        // 到本地地区库里找中国气象地区编码,可以把序列化数据直接反序列化后放到本文件里,会更快

        $area = file_get_contents("area.php");

        $area = unserialize($area);

        //print_r($area);

        $province = array();

        foreach($area as $k => $v){

            $province[$k] = $v[&#39;level0&#39;];

        }

 

        $pid = array_search($this->province,$province);

        if($pid !== false){

            $citys = $area[$pid][&#39;level1&#39;];

            $cityid = array_search($this->city,$citys);

            if($cityid !== false){

                $code = &#39;101&#39;.$cityid.&#39;01&#39;;

            }else{

                $code = &#39;101&#39;.$pid.&#39;0101&#39;;

            }

        }

        return $code;

    }

}

 

/*

    纯真ip库返回的地区格式如下:

    xx省xx市 或者 xx市 如果是自治区则为:新疆乌鲁木齐市,分割省市极麻烦

*/

 

$weather = new weather();

// php的扩展iplocation

$addrarr = iplocation_fetch(weather::getIP());

$addr = iconv(&#39;gbk&#39;,&#39;utf-8&#39;,$addrarr[&#39;province&#39;]);

$weather->setArea($addr);

$code = $weather->getAreaCode();

 

// 尝试从redis里读取天气数据

$redis_host = &#39;127.0.0.1&#39;;

$redis_port = 6379;

/* redis connect */

$redis = new Redis();

$redis->connect($redis_host, $redis_port);

 

$data = $redis->get($code);

if(!$data){

    // 从中国气象去抓,并存入redis

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, "http://m.weather.com.cn/data/{$code}.html");

    curl_setopt($curl, CURLOPT_HEADER, 0);

    curl_setopt ($curl, CURLOPT_TIMEOUT, 30 );

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $data = curl_exec($curl);

    curl_close($curl);

    if($data){

        $redis->set($code,$data);

        $redis->EXPIRE($code,3600);

    }else{

        echo &#39;weather.com.cn 连接超时&#39;;

    }

}

print_r($data);

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)

Features and Advantages of C Language: Why is it one of the most popular programming languages? Features and Advantages of C Language: Why is it one of the most popular programming languages? Feb 23, 2024 am 08:39 AM

Features and Advantages of C Language: Why is it one of the most popular programming languages? As a general-purpose high-level programming language, C language has many unique features and advantages, which is why it has become one of the most popular programming languages. This article will explore the characteristics and advantages of C language, as well as its wide application in various fields. First of all, C language has concise syntax and clear structure. Compared with other programming languages, the syntax of C language is relatively simple and easy to understand and learn. It uses the characteristics of natural language to enable programmers to

How to set the weather forecast on Huawei mobile phones on the desktop Detailed explanation: Tutorial on adding desktop widgets to mobile phones How to set the weather forecast on Huawei mobile phones on the desktop Detailed explanation: Tutorial on adding desktop widgets to mobile phones Mar 02, 2024 pm 12:34 PM

Since December 2021, Huawei & Honor mobile phones have launched the Vientiane desktop widget function. Many convenient functions, visually optimized desktop controls, etc. have been added to many users’ mobile desktops; by August this year, the two major merchant platforms also opened up sports and health data, weather data, music data, system data, etc., allowing users to use their mobile desktops The interactive operation is more convenient, faster and more interesting, allowing users to DIY and create their own personalized desktop. Mobile desktop after adding widgets Recently, many Huawei mobile phone users have reported that they are not clear about how to add desktop widgets on Huawei and Honor mobile phones, complaining that the process is too complicated and cumbersome. In order to help everyone solve this problem, Qian Shuxian has prepared a detailed operation process, hoping to

C drive space is running out! 5 efficient cleaning methods revealed! C drive space is running out! 5 efficient cleaning methods revealed! Mar 26, 2024 am 08:51 AM

C drive space is running out! 5 efficient cleaning methods revealed! In the process of using computers, many users will encounter a situation where the C drive space is running out. Especially after storing or installing a large number of files, the available space of the C drive will decrease rapidly, which will affect the performance and running speed of the computer. At this time, it is very necessary to clean up the C drive. So, how to clean up C drive efficiently? Next, this article will reveal 5 efficient cleaning methods to help you easily solve the problem of C drive space shortage. 1. Clean up temporary files. Temporary files are temporary files generated when the computer is running.

Guide to efficient conversion of golang coding practices Guide to efficient conversion of golang coding practices Feb 20, 2024 am 11:09 AM

Title: Efficient Practice Guide for Go Language Encoding Conversion In daily software development, we often encounter the need to convert text in different encodings. As an efficient and modern programming language, Go language provides a rich standard library and built-in functions, making it very simple and efficient to implement text encoding conversion. This article will introduce practical guidelines on how to perform encoding conversion in the Go language and provide specific code examples. 1.UTF-8 encoding and string conversion In Go language, strings use UTF-8 encoding by default

In-depth understanding of the functions and features of Go language In-depth understanding of the functions and features of Go language Mar 21, 2024 pm 05:42 PM

Functions and features of Go language Go language, also known as Golang, is an open source programming language developed by Google. It was originally designed to improve programming efficiency and maintainability. Since its birth, Go language has shown its unique charm in the field of programming and has received widespread attention and recognition. This article will delve into the functions and features of the Go language and demonstrate its power through specific code examples. Native concurrency support The Go language inherently supports concurrent programming, which is implemented through the goroutine and channel mechanisms.

Comparing the cost of learning Python and C++: Which one is more worth the investment? Comparing the cost of learning Python and C++: Which one is more worth the investment? Mar 25, 2024 pm 10:24 PM

Python and C++ are two popular programming languages, each with its own advantages and disadvantages. For people who want to learn programming, choosing to learn Python or C++ is often an important decision. This article will explore the learning costs of Python and C++ and discuss which language is more worthy of the time and effort. First, let's start with Python. Python is a high-level, interpreted programming language known for its ease of learning, clear code, and concise syntax. Compared to C++, Python

Deep mining: using Go language to build efficient crawlers Deep mining: using Go language to build efficient crawlers Jan 30, 2024 am 09:17 AM

In-depth exploration: Using Go language for efficient crawler development Introduction: With the rapid development of the Internet, obtaining information has become more and more convenient. As a tool for automatically obtaining website data, crawlers have attracted increasing attention and attention. Among many programming languages, Go language has become the preferred crawler development language for many developers due to its advantages such as high concurrency and powerful performance. This article will explore the use of Go language for efficient crawler development and provide specific code examples. 1. Advantages of Go language crawler development: High concurrency: Go language

Applying physically coupled graph neural networks to improve precipitation forecasting skills at the Institute of Atmospheric Physics, Chinese Academy of Sciences Applying physically coupled graph neural networks to improve precipitation forecasting skills at the Institute of Atmospheric Physics, Chinese Academy of Sciences Jan 25, 2024 pm 03:42 PM

Editor | In the era of ScienceAI large models, the effects of purely data-driven meteorological and climate models are gradually catching up to or even surpassing numerical models. However, existing large-scale meteorological and climate models still have some problems. For example, the physical consistency in the model is not high enough, which limits the ability to predict complex weather and climate phenomena such as precipitation. In addition, the forecast effect of divergent wind is not satisfactory. These issues require further research and improvement to improve the prediction accuracy and reliability of the model. At present, combining physics, atmospheric dynamics and deep learning models is an important way to solve the bottleneck problem. Recently, the team of researcher Huang Gang from the Institute of Atmospheric Physics, Chinese Academy of Sciences, based on the data and computing power support of the Earth System Numerical Simulation Facility (Huan), analyzed the coupling relationship between physical variables from the perspective of

See all articles