php根据访问者ip地址获取天气预报信息

今天有空了,将根据访问用户IP地址自动获取天气预报下载中捉去sina天气数据的php代码更新了,如下所示

header("content-type","text/html;charset=gb2312");
ini_set('date.timezone','PRC');//设置时间为中国时区
function removeHTML($str)
{
$str=preg_replace("/<[^>]+>/","",$str);
return $str;
}
function getip(){
  $ip =$_SERVER["http_x_forwarded_for"];
  if(empty($ip)) $ip=$_SERVER["remote_addr"];
  return $ip;
}
function getWeather(){
    $ip = getip();
$json = "var weather={success:false};";
$addr="桂林";
//if (!empty($ip)){
    //$arr=explode(".",$ip);
    //$ipNum = 0; $pow = 256;
    //$ipNum=$arr[0]*pow($pow,3)+$arr[1]*pow($pow,2)+$arr[2]*pow($pow,1)+$arr[3];
    /*
     执行Sql语句获取城市地址,并保存到$addr变量中
 "select城市地址from表whereip结束地址>=" .$ipNum.+ "andip开始地址=".$ipNum
*/
if (!empty($addr)){
$htmlBody=file_get_contents("http://php.weather.sina.com.cn/search.php?city=".$addr); 
if(preg_match_all("/".$addr.",([^,]+),([^,]+),风力:([^']+)/i",$htmlBody,$m,PREG_SET_ORDER)){
preg_match_all("/
    \\s*风向:([^<]+)<\\/li>/i",$htmlBody,$dirm,PREG_SET_ORDER);
    $json = "{success:true,addr:'".$addr."',weathers:[{d:'" .date("Y-m-d"). "'"
                       . ",weather:'" . $m[0][1]."',tmp:'" . $m[0][2]
       . "',dir:'". $dirm[0][1]."',strong:'".$m[0][3]."'}";
        if(preg_match_all("/([\\s\\S]+?)<\\/div>/i",$htmlBody,$m,PREG_SET_ORDER)){
    $htmlBody=$m[0][1];
    if(preg_match_all("/]*>([\\s\\S]+?)<\\/table>/i",$htmlBody,$m,PREG_SET_ORDER)){
    $idx=count($m);
    $darr=getdate();
    for($i=0;$i<$idx;$i++){
    if(preg_match_all("/([\\s\\S]+?)<\\/td>/i",$m[$i][1],$mc,PREG_SET_ORDER)){
       $dw=$mc[4][1];$nw=$mc[5][1];
       if($dw!=$nw)$dw.=" 转 ".$nw;
       $dtmp=removeHTML($mc[6][1]);$ntmp=removeHTML($mc[7][1]);
       $ddir=$mc[8][1];$ndir=$mc[9][1];
       if($ddir!=$ndir)$ddir.=" 转 ".$ndir;
       $json .= ",{d:'" .date("Y-m-d",mktime(0,0,0,$darr["mon"],$darr["mday"]+$i+1,$darr["year"]))
                ."',weather:'".$dw."',tmp:'".$dtmp."~".$ntmp. "',dir:'".$ddir."'}";
    }
    }
    }
    }
    $json.="]};";
    }
        }
        return $json;
    }
    echo getWeather();
    ?>

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:php根据访问者ip地址获取天气预报信息

评论(2)Web开发网
阅读(256)喜欢(0)PHP/apache/Perl