How to use PHP to implement weather forecast function

WBOY
Release: 2023-06-27 20:24:01
Original
1777 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!