PHP天气查询1

<?php

$city_name=$_GET['city'];

//用正则在city.txt中查找相应城市的天气城市代码
$city_name=trim(ereg_replace("[ ]{1,}","",$city_name));
$time_file="city.txt";

$city_all=file_get_contents($time_file);
$preg="|$city_name,(.*)/s|i";
preg_match_all($preg,$city_all,$cn, PREG_SET_ORDER);
$city_n=trim($cn[0][1]);


if($city_n)
{
$nowtime=date("Y-m-d");

$file = "cache/$city_name.txt";

//获取文件的最后修改日期
if(file_exists($file))
{
$last_time=date("Y-m-d",filemtime($file));
}
else{
$last_time=date("Y-m-d");
}
//新建保存匹配数组
$records=null;


//如果文件存在,或还没过期,则直接读取缓存数据
if (file_exists($file) && $last_time==$nowtime)
{
 
    $records = unserialize(file_get_contents($file));

}
else
{

//以下就是如何在网站上 获取天气资料,,小偷部分!感觉其中的preg_match_all功能很强大

$data=file_get_contents("http://weather.msn.com/local.aspx?wealocations=wc:$city_n");
$preg="|<td class=/"icon/"><img src=/"(.*)/" width=.*class=/"hilo/"><tr><th>Hi:<//th> <td>(.*)&#176;<//td><//tr><tr><th>Lo:<//th> <td>(.*)&#176;<//td><//tr><//table>.*class=/"skytext/" colspan=/"3/">(.*)<//td>|U";

 preg_match_all($preg,$data,$records);
 unset ($records[0][0]);

   //序列化组
   $OUTPUT = serialize($records);
   //打开文件,
    $fp = fopen($file,"w");
    //把数组写进文件
    fputs($fp, $OUTPUT);
    //关闭
    fclose($fp);
 
 }
 
   $image=$records[1][0];
   $resulta=$records[2][0];
   $resultb=$records[3][0];
   $resultc=$records[4][0];
 $reString="<table width=/"100%/">
          <tr bgcolor=/"#cccccc/">
            <td width=/"50%/"><font size=/"4/">$city_name</font></td>
            <td width=/"50%/"><div align=/"right/"><font size=/"3/">$nowtime</div></font></td>
          </tr>
          <tr>
            <td rowspan=/"2/"><img src='".$image."' //></td>
            <td><font size=/"3/">".$resulta."-".$resultb."(F)</fong></td>
          </tr>
          <tr>
            <td colspan=/"2/"><font size=/"3/">".$resultc."</fong></td>
          </tr>
          </table>";
}
else
{
  $reString="<table width=/"100%/">
          <tr bgcolor=/"#cccccc/">
            <td width=/"50%/"><font size=/"4/">The city: $city_name hasn`t  been found!</font></td>
          </tr>
          </table>";
}
echo iconv("gb2312","utf-8",$reString);

?> 

主要是把当天的做个缓存,这样第2次访问同一城市的时候的话就比较快了。虽然不是什么好代码,但是对与刚刚学习PHP的人还是一个蛮好的例子,特别是里面的正则表达式的应用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值