=波波日志 > PHP/apache/Perl > php根据访问者ip地址获取天气预报信息=

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

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

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/apache/Perl 作者:波波 日期:2010-04-29 【评论:2】 
     
      • 求助下

    • 日期:2010-12-2 16:53:34  IP:111.79.*.*
      求助下,刚复制了拿来看了下,发现用不了,楼主
      管理员回复(2010-12-3 8:52:01)
      不好意思哦~~最近比较忙,没时间更新php版本的代码,因为主要是sina的天气预报页面经常变更结构,所以他们那边一改变结构就取不到数据,需要重新更正过正则表达式的结构

      下面这篇文章是最新的asp.net获取新浪的天气预报的,你对照修改下php的正则表达式和代码结构

      使用新浪天气预报接口获取天气预报信息


    • 日期:2010-12-5 13:36:34  IP:124.160.*.*
      PHP是好东西,应该好好研究一下
      管理员回复(2010-12-6 8:47:20)
      是啊,不过我还是asp.net和asp的多。php就半桶水,O(∩_∩)O~

    发表留言
    • *昵称:
    • 头像:
    • 电子邮件: [留下您的邮件,方便管理员回复您。]
    • 个人网站: *验证码:
    声明:本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载或引用的作品侵犯了您的权利,请通知我们,我们会及时删除!
    Powered by showbo,©2012WEB编程网桂ICP备05005887号 京公网安备1101055090