php定位和天气,php – 根据用户所在地显示天气

这将使用

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");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值