fsockopen函数发送post请求获得网页信息–天气预报

取得新浪天气预报网页的城市当日信息.
共有两个文件:
tianqi.html:利用下拉菜单跳转到网页获得天气预报信息,返回信息到浮动帧内;
<script type="text/javascript"><!--mce:0--></script>
<form action="get_tianqi.php" accept-charset="UNKNOWN" enctype="application/x-www-form-urlencoded" method="post">
<select name="city"> <option selected="selected">请选择一个城市</option> <option value="广州">广州</option> <option value="肇庆">肇庆</option> <option value="湛江">湛江</option> <option value="深圳">深圳</option> <option value="东莞">东莞</option></select>
<input name="url" type="hidden" />
</form>

get_tianqi.php:取得天气预报信息
<?php
/* 此程序是从新浪网的天气网页http://php.weather.sina.com.cn/search.php?city=中取得某个城市的天气预报*/
ob_start(); //启动输出缓冲
function request_url($url,$method='POST') {
$url = parse_url($url); //解析url地址,取得host,path,port,query等
if (!$url) return "couldn't parse url";
if (!isset($url['port'])) { $url['port'] = ""; }
if (!isset($url['query'])) { $url['query'] = ""; }
//连接服务器
$fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
if (!$fp) return "不能连接".$url['host']."服务器";
//发送请求
fputs($fp, sprintf("$method %s%s%s HTTP/1.0\n", $url['path'],
$url['query'] ? "?" : "", $url['query']));
fputs($fp, "Host: $url[host]\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
fputs($fp, "Connection: close\n\n");
//获得请求后返回的内容
$line = fgets($fp,1024);
if (!eregi("^HTTP/1\.. 200", $line)) return;
$results = "";
while(!feof($fp)) {
$line = fgets($fp,1024);
$results .= $line;
}
fclose($fp);
return $results;
}
//获得从其它网页传送过来的url(带查询字串)
if (!$_REQUEST['url']) {
echo "请添加一个url";
exit;
}else{
$url=$_REQUEST['url'];
}
$content=request_url($url); //取得请求后的网页内容
$start=strpos($content,"<! 天气状况 begin -->");//取得天气预报的截取段
$end=strpos($content,"<!-- 天气状况 end -->");
$len=$end-$start;
$b=substr($content,$start,$len); //截取得指定内容
//从上面的截取段中取得城市今日天气预报的截取段
$sub_start=strpos($b,"
<div class="\"City_Data\"">");
$sub_end=strpos($b,"
<div class="\"Weather_SM\"">");
$len2=$sub_end-$sub_start;
$c=substr($b,$sub_start,$len2);
$d=split("\n",$c); //去掉换行符
//print_r($d);
$e="";
foreach ($d as $key=>$value){
$value=strip_tags($value); //去掉html标记
$e.=$value;
if ($key==2) {
$e.="
";
}
}
echo $e;
ob_end_flush();
?></div>
</div>

评论列表

博百优
我来你了http://www.dangr.cn
2010-05-10 15:14:00