这将使用
Data Science Toolkit的开源
IP2Coordinates service从其IP地址获取用户的邮政编码.
那里有更准确的地理位置API,但是这个API绝对免费且易于使用.如果我在生产站点上开发这个,我会使用HTML5 Geolocation作为我的主要方法,并回退到更好的IP地理定位器,如Max Mind.
请注意,这仅适用于您网站的美国用户.您应该将更详细的数据传递给其他Yahoo位置API以获取其中一个WOEID(或选择不同的天气API).
这是给你的代码.把它放在示例代码中的
//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('
Your zip code is: %s
', $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('
Sorry, this app does not work in %s.
', $raw_geocode->$user_ip->country_name);}
//Print the raw data for debugging.
printf('
%s', print_r($raw_geocode, true));
现在将示例代码中以$data =开头的行更改为:
$data = get_data("http://weather.yahooapis.com/forecastrss?p={$zip_code}&u=f");