Home Backend Development PHP Tutorial How to use PHP to implement weather forecast function

How to use PHP to implement weather forecast function

Jun 27, 2023 pm 05:54 PM
php Function weather forecast

As a popular back-end programming language, PHP is widely popular in the field of web development. The weather forecast function is a common web application scenario. Implementing the weather forecast function based on PHP is relatively simple and easy to understand. This article will introduce how to use PHP to implement the weather forecast function.

1. Obtain weather data API

To implement the weather forecast function, you first need to obtain weather data. We can use third-party weather APIs to obtain real-time, accurate weather data. At present, the mainstream weather API providers in China include the free "Xinzhi Weather" and the paid "Aggregation Data Weather".

Taking Xinzhi Weather as an example, we first apply for a developer account on its official website and obtain a free API key. Developer account registration is free, and each account has 1,000 free calls per day by default.

Xinzhi Weather provides many types of APIs, including real-time weather, hourly weather, daily weather, etc. Just select the corresponding API according to actual needs. In this article, we choose to use the real-time weather API to obtain current weather data.

2. Parse JSON format data

The weather data returned by Xinzhi Weather is returned in JSON format. Therefore, we need to learn how to parse JSON format data.

In PHP, you can use the built-in function json_decode() to convert JSON format data into an object or array. For example:

$json_string = '{"name":"Peter","age":21,"city":"New York"}';
$data = json_decode($json_string);
echo $data->name;
Copy after login

In the above code, we convert a JSON format string into the object $data, and then output the value "Peter" of its name attribute.

If you do not want to convert JSON data to an object, but want to convert it to an array, you can set the second parameter of the json_decode() function to true. For example:

$json_string = '{"name":"Peter","age":21,"city":"New York"}';
$data = json_decode($json_string, true);
echo $data['name'];
Copy after login

3. Use CURL to get data

To get data from the API server, we can use the CURL library in PHP. CURL is a file transfer protocol based on the HTTP protocol, often used to interact with web servers, receive and send data.

In PHP, you can use the curl_init() function to initialize a CURL session, and then use the curl_setopt() function to set some parameters, such as request URL, request method, request header information, request body data, etc. Finally, use the curl_exec() function to execute the CURL session and obtain the data returned by the server.

For example, the following code is an example of using CURL to obtain real-time weather data from the Xinzhi Weather API:

$url = 'https://api.seniverse.com/v3/weather/now.json';
$params = [
    'key' => 'your-api-key', // 替换成你自己的API key
    'location' => '北京',
    'language' => 'zh-Hans',
    'unit' => 'c'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
echo '当前城市:' . $data['results'][0]['location']['name'] . '<br>';
echo '当前温度:' . $data['results'][0]['now']['temperature'] . '℃<br>';
echo '天气状况:' . $data['results'][0]['now']['text'];
Copy after login

In the above code, we use the http_build_query() function to convert the parameter array is the query string in the URL to send the request parameters to the API server. Then use the json_decode() function to parse the JSON format data returned by the server into an array, and finally output the city, temperature and weather conditions information.

4. Use template syntax to output data

After we obtain the weather data, we need to render it to the front-end page. In order to separate the data from the front-end page, we can use PHP's template engine to achieve this.

Common PHP template engines include Smarty, Blade, Twig, etc. Here we take Blade as an example to introduce how to render weather data to the front-end page.

First, we define a placeholder in the Blade template to display weather data. For example:

<div class="weather">
  <p>当前城市:{{ $city }}</p>
  <p>当前温度:{{ $temperature }}℃</p>
  <p>天气状况:{{ $text }}</p>
</div>
Copy after login

Then, we output the obtained weather data to the placeholder in the PHP code. For example:

$data = json_decode($response, true);
$view = new JenssegersBladeBlade(__DIR__.'/views', __DIR__.'/cache');
echo $view->make('weather', [
    'city' => $data['results'][0]['location']['name'],
    'temperature' => $data['results'][0]['now']['temperature'],
    'text' => $data['results'][0]['now']['text'],
])->render();
Copy after login

In the above code, we first use the constructor of Blade to create a view object $view. Among the constructor parameters, the first parameter is the path to the view folder, and the second parameter is the path to the cache folder.

Then, we use the make() method of the view object to pass in the view file name and the data to be rendered to generate a view instance. Finally, the view content is output using the render() method of the view instance.

5. Complete code example

Finally, we integrate the above code into a complete PHP file to implement the weather forecast function. The complete code is as follows:

<?php

require_once 'vendor/autoload.php';

$url = 'https://api.seniverse.com/v3/weather/now.json';
$params = [
    'key' => 'your-api-key', // 替换成你自己的API key
    'location' => '北京',
    'language' => 'zh-Hans',
    'unit' => 'c'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

$view = new JenssegersBladeBlade(__DIR__.'/views', __DIR__.'/cache');
echo $view->make('weather', [
    'city' => $data['results'][0]['location']['name'],
    'temperature' => $data['results'][0]['now']['temperature'],
    'text' => $data['results'][0]['now']['text'],
])->render();
Copy after login

In this sample code, we introduce the Blade template engine dependency through the vendor/autoload.php file. We create a blade template in the views folder with placeholders for rendering weather data. Finally, we pass the data into the template through the view object and render the final weather forecast page.

6. Conclusion

Using PHP to implement the weather forecast function is a common web development requirement. With the help of third-party weather API, we can easily obtain weather data. Then, use the CURL library to obtain data, the json_decode() function to parse the data, and the Blade template engine to output the data, and the weather forecast function can be completely realized. Although the above steps are a bit cumbersome, they are relatively easy to get started once you master them.

The above is the detailed content of How to use PHP to implement weather forecast function. For more information, please follow other related articles on the PHP Chinese website!

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
4 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
1670
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
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

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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.

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.

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.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis 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.

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.

See all articles