现在很多比较好用的天气接口都是收费的,自己写了一个可以通过ip获取当前城市并且调取天气信息的函数,用的是新浪的接口,借用了网上的一些资源,现在还能用,这里面还包括了获取客户端ip,将xml转换为数组函数
备注:新浪的接口的城市名是需要gb2312编码的,所以调取接口的时候要先编码一下
function vget($url){ // 模拟获取内容函数
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_HTTPGET, 1); // 发送一个常规的Post请求
//curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie_file); // 读取上面所储存的Cookie信息
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
//echo '错误返回'.curl_error($curl);
}
curl_close($curl); // 关闭CURL会话
return $tmpInfo; // 返回数据
}
/**
* 获取客户端IP地址
* @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @return mixed
*/
function get_client_ip($type = 0) {
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = ip2long($ip);
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
/**
* [getWeather 将xml转换为数组]
* @param string $xml [description]
* @return [type] [description]
*/
function xml2arr($xml){
$obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($obj);
$arr = json_decode($json, true);
return $arr;
}
/**
* [getWeather 通过ip获取城市地址]
* @param string $ip [description]
* @return [type] [description]
*/
function getIpCity($ip){
if(!$ip) $ip = get_client_ip(); //获取客户端IP
$ip = '123.123.123.123';
//通过ip获取城市并存储session
$ip_url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip;
$ip_info = json_decode(vget($ip_url));
$city = $ip_info->city;
if(session('weather_city') == '' && $city != ''){
session('weather_city',$city);
}
return $city;
}
/**
* [getWeather 通过城市获取未来三天天气]
* @return [type] [description]
*/
function getWeather()
{
$city = getIpCity();
$list = array();
if($city != ''){
for($i = 0;$i<3; $i++){
$weather_url = "http://php.weather.sina.com.cn/xml.php?city=" . iconv("utf-8","gb2312",$city) . "&password=DJOYnieT8234jlsK&day=".$i;
$weather_info = vget($weather_url);
$weather_info = xml2arr($weather_info);
$list[$i] = $weather_info['Weather'];
}
}
return $list;
}