您现在的位置是: 首页 > 天气资讯 天气资讯
天气预报代码_php天气预报代码
tamoadmin 2024-12-15 人已围观
简介可以借由php的api或者preg_match_all偷偷撷取去达成目的这里给你一段我给台湾朋友有一段源码<?phpheader(\"Content-Type:?text/html;?charset=utf-8\");function?getWeather($city){$toURL?=?\"$city.htm\";$post?=?array();$ch?=?curl_init();$opt
可以借由php的api或者preg_match_all偷偷撷取去达成目的
这里给你一段我给台湾朋友有一段源码
<?phpheader(\"Content-Type:?text/html;?charset=utf-8\");
function?getWeather($city){
$toURL?=?\"
$city.htm\";
$post?=?array();
$ch?=?curl_init();
$options?=?array(
CURLOPT_REFERER=>'',
CURLOPT_URL=>$toURL,
CURLOPT_VERBOSE=>0,
CURLOPT_RETURNTRANER=>true,
CURLOPT_USERENT=>\"Mozilla/4.0?(compatible;)\",
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>_build_query($post),
);
curl_setopt_array($ch,?$options);
$result?=?curl_exec($ch);?
curl_close($ch);
//连接中央气象局
echo?'<pre>';
preg_match_all('/<table?class=\"FcstBoxTable01\"?[^>]*[^>]*>(.*)<\/div>/si',$result,?$matches,?PREG_SET_ORDER);
preg_match_all('/<td?nowrap=\"nowrap\"?[^>]*[^>]*>(.*)<\/td>/si',$matches[0][1],?$m1,?PREG_SET_ORDER);
$m2?=?explode('</td>',$m1[0][1]);
//?print_r($m2);//取得每日资料m2[0~6]
$weather?=?array();
for($i=0;$i<=6;$i++){
preg_match_all('/src=[^>]*[^>](.*)/si',$m2[$i],?$m5,?PREG_SET_ORDER);//取得天气图档
$m6?=?explode('\"',$m5[0][0]);
$wi='
($m6[1],'\.\./\.\./');
$wtitle?=?$m6[3];
print_r($wtitle);$weather[$i]['date']?=?date(\"m-d\",?mktime(0,?0,?0,?date(\"m\"),?date(\"d\")+$i,date(\"Y\")));
$weather[$i]['temperature']?=?trim(strip_tags($m2[$i]));
$weather[$i]['title']?=?$wtitle;
$weather[$i]['img']?=?$wi;
}
return($weather);
}
$weather=getWeather(\"Taipei_City\")?;?
print_r($weather);
//?header(\"Location:loc.php\");
>首先
$toURL?=?\"://.cwb.gov.tw/V7/forecast/taiwan/inc/city/$city.htm\";这里是读取资料的网址
上面的是台湾中央气象局
preg_match_all('/<table?class=\"FcstBoxTable01\"?[^>]*[^>]*>(.*)<\/div>/si',$result,?$matches,?PREG_SET_ORDER);preg_match_all('/<td?nowrap=\"nowrap\"?[^>]*[^>]*>(.*)<\/td>/si',$matches[0][1],?$m1,?PREG_SET_ORDER);
这里是截取台湾中央气象局网页信息table class=\"FcstBoxTable01\" [^>]*[^>]*>(.*)<\/div>的资料以及<td nowrap=\"nowrap\" [^>]*[^>]*>(.*)<\/td>的资料分别是1天跟1周
$m2?=?explode('</td>',$m1[0][1]);//?print_r($m2);//取得每日资料m2[0~6]
这里是取得每日的资料
preg_match_all('/src=[^>]*[^>](.*)/si',$m2[$i],?$m5,?PREG_SET_ORDER);//取得天气图档这里是取得天气的图档
$m6?=?explode('\"',$m5[0][0]);$wi='
($m6[1],'\.\./\.\./');
$wtitle?=?$m6[3];
print_r($wtitle);$weather[$i]['date']?=?date(\"m-d\",?mktime(0,?0,?0,?date(\"m\"),?date(\"d\")+$i,date(\"Y\")));
$weather[$i]['temperature']?=?trim(strip_tags($m2[$i]));
$weather[$i]['title']?=?$wtitle;
$weather[$i]['img']?=?$wi;
这里是返回的网址,日期,标题,图档等等的资料
$weather=getWeather(\"Taipei_City\")?;?print_r($weather);
然后这里是显示出地区的一周天气预报
结论:就是如果你想从网站上面截取天气预报
在php可以是用preg_match_all(网页的表格table,表格的列数tr,表格的栏位td,或者更加广泛的标签div等等获取)
我昨天刚做了个,本来打算自己用,你既然问,就分享了吧!
PS:因为我是菏泽人,所以,如果你什么都不填,就显示菏泽天气。
如果想显示别的,直接输入就行,比如"香港",然后提交就OK了
://young.boustead.edu.cn/data/shunzi/tq.php
不知道是否合乎楼主的意愿(不用JS)