PHP天气预报系统核心代码

Copyright: piao2010.com

转载请保留版权:http://www.piao2010.com 谢谢!

昨天接到公司新任务要做个天气预报查询网站,因为公司不可能直接获取天气相关数据,那就只能是抓取网络上的数据进行处理了,或者说直接跳转到某个网站的相应页面。后者处理起来简单,我这里用的是正则表达式来远程提取相关数据存入自己的数据库的方式实现。天气预报数据取自www.weather.com.cn

核心代码如下:

<!DOCTYPE html PUBLIC-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>天气预报</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8/>
</head>
<body>
<?php
$id =101010100;//从数据库或者数组获取城市对应的编码,这里以北京为例
$file = file_get_contents(”http://www.weather.com.cn/html/weather/{$id}.shtml”);//读取远程数据
preg_match_all(/<div class=”weatherwapper”>(.*?)<div class=”right_content”>/is”,$file,$main_content);//取有价值的部分
preg_match_all(/<h2 class=”tit01_contentl” >(.*?)</h2>/is”,$main_content[0][0],$tmp_date);//提取包含日期的部分
preg_match_all(/今天是(.*?)/is”,$tmp_date[0][0],$date);
$date = strip_tags($date[1][0]);
print_r (<br />.$date);
preg_match_all(/<div class=”left_contenttopl”>(.*?)/is”,$main_content[0][0],$tmp_city);//提取城市名称
preg_match_all(/<strong>(.*?)</strong>/is”,$tmp_city[0][0],$city);
$city = strip_tags($city[0][0]);
print_r(<br />.$city);
preg_match_all(/<div class=”right_contenttopl”>(.*?)</div>/is”,$main_content[0][0],$tmp_post);//提取邮编等信息
preg_match_all(/<dl>(.*?)</dl>/is”,$tmp_post[0][0],$tmp_post);
$post = strip_tags($tmp_post[0][0]);
print_r(<br />.$post);
preg_match_all(/<div class=”box_contenttodayinwea” id=”c_1_1″>(.*?)<div class=”box_hist”>/is”,$main_content[0][0],$tmp_weather);
$weather = str_replace(”气温趋势”,",strip_tags($tmp_weather[0][0]));//删除”气温趋势”(以图片方式输出的数据不保留)
$weather = str_replace(”今日风力”,”",strip_tags($weather));//删除”今日风力”(以图片方式输出的数据不保留)
print_r(<br />.$weather);
preg_match_all(/<div class=”fut_weather” id=”dd_0″>(.*?)<div class=”box_contentl scene_weather”>/is”,$main_content[0][0],$tmp_future);//提取未来7天的天气情况
preg_match_all(/<div class=”fut_weatherbox7″>(.*?)</div>/is”,$tmp_future[0][0],$future);
foreach($future[0] as &$value) {
  $value = strip_tags($value);
  print_r(<br />.$value);
 }
?>
</body>
</html>

城市对应的代码可以事先收集好放在数据库里,取得远程天气数据以后插入本地数据库就好了,下一次访问的时候判断一下本地数据是不是当日的,不是的话重新提取远程数据。一个简易的天气预报系统就完成了,主要就是正则表达式的运用,功能比较简单,可以扩展一下,有个缺点:远程页面的HTML代码修改了对应的正则表达式也要修改。

  1. tracy 说:

    给大哥踩BLOG是义不容辞的

    [回复]

    admin 回复:

    呵呵,谢谢支持哈!

    [回复]

  2. 南柯一梦 说:

    来踩踩,这个貌似挺有用的~

    [回复]

  3. Ray 说:

    看看,还不错

    [回复]

  1. There are no trackbacks for this post yet.

Leave a Reply



无觅相关文章插件,快速提升流量