您的位置:首页 > 编程语言 > PHP开发

PHP 用正则表达式preg_match_all抓取天气预报

2014-07-14 16:51 1566 查看
代码如下:

<?php

$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-Type: text/html; charset=utf-8"
)
);
$context = stream_context_create($opts);
//设定要抓取的页面(本例为北京天气)
$url = "http://www.weather.com.cn/html/weather/101010100.shtml";
$file = file_get_contents($url, false, $context);
preg_match_all('/<table class="yuBaoTable"[^>]*>(.*)<\/table>/isU',$file,$out1);
for($i = 0; $i < count($out1[1]); $i ++)
{
preg_match_all('/<tr[^>]*>(.*)<\/tr>/isU',$out1[1][$i],$out2);
preg_match_all('/<td[^>]*>\s*<a[^>]*>(.*)<\/a>\s*<\/td>/isU',$out2[1][0],$out3);
echo "【".date("Y-m")."-".$out3[1][0]."】<br />";
echo "白天:".$out3[1][2]." ".$out3[1][3]." ".$out3[1][4]." ".$out3[1][5]."<br />";
preg_match_all('/<td[^>]*>\s*<a[^>]*>(.*)<\/a>\s*<\/td>/isU',$out2[1][1],$out4);
if($out4[1][2])
{
echo "夜间:".$out4[1][2]." ".$out4[1][3]." ".$out4[1][4]." ".$out4[1][5]."<br />";
}
}
?>

运行效果:

http://1.xinyuan88.sinaapp.com/weather.php
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息