use*_*771 5 php wordpress location weather
我使用的代码根据我插入的Yahoo API URL更改了我的wordpress网站的背景.反正有没有任何数据库自动显示访客天气?我虽然使用谷歌的API,但我是编程的新手,不知道如何将其实施到我的网站.请帮忙!代码可以在这里查看:http://css-tricks.com/using-weather-data-to-change-your-websites-apperance-through-php-and-css/
请彻底,因为我是PHP的新手谢谢!
您需要一个API来将访问者IP地址映射到位置(ipapi.co),另一个用于获取该位置的天气预报(openweathermap.org).下面的代码是针对php(服务器端):
# Part 1 (get latitude & longitude)
$ip = '1.2.3.4';
$api_1 = 'https://ipapi.co/' . $ip . '/latlong/';
$location = file_get_contents($api_1);
$point = explode(",", $location);
# Part 2 (get weather forecast)
$api_2 = 'http://api.openweathermap.org/data/2.5/weather?lat=' . $point[0] . '&lon=' . $point[1] . '&appid=API_KEY';
$weather = file_get_contents($api_2);
Run Code Online (Sandbox Code Playgroud)
这将使用开源从他们的IP地址得到一个用户的邮政编码IP2Coordinates服务从数据科学工具包.
那里有更准确的地理位置API,但是这个API绝对免费且易于使用.如果我在生产站点上开发这个,我会使用HTML5 Geolocation作为我的主要方法,并回退到更好的IP地理定位器,如Max Mind.
请注意,这仅适用于您网站的美国用户.您应该将更详细的数据传递给其他Yahoo位置API以获取其中一个WOEID(或选择不同的天气API).
这是给你的代码.将其放在<?php
示例代码中的标记之后.一旦你确定它正在工作,请注释掉所有开头的行print
.
//Get the user's IP address
$user_ip = $_SERVER['REMOTE_ADDR'];
//The Data Science Toolkit URL
$url = 'http://www.datasciencetoolkit.org/ip2coordinates/';
//Find the user's location from their IP.
//*** You need the get_data function from the sample code
$raw_geocode = json_decode( get_data( $url . $user_ip) );
//Check if the user is in the US
if ('US' === $raw_geocode->$user_ip->country_code) {
//If yes, store their zip code in a variable, and print it
$zip_code = $raw_geocode->$user_ip->postal_code;
printf('<p>Your zip code is: %s</p>', $raw_geocode->$user_ip->postal_code);
} else {
//If the user isn't in the US, set a sip code that will work.
$zip_code = '97211';
//and print an error
printf('<p>Sorry, this app does not work in %s.</p>', $raw_geocode->$user_ip->country_name);
}
//Print the raw data for debugging.
printf('<pre>%s</pre>', print_r($raw_geocode, true));
Run Code Online (Sandbox Code Playgroud)
现在更改示例代码中$data =
以此为开头的行:
$data = get_data("http://weather.yahooapis.com/forecastrss?p={$zip_code}&u=f");
Run Code Online (Sandbox Code Playgroud)