php函数fsockopen获取新浪天气预报

取得新浪天气预报网页的城市当日信息.
共有两个文件:
tianqi.html:利用下拉菜单跳转到网页获得天气预报信息,返回信息到浮动帧内;
<html>
<head></head>
<script>
<!--
function go(){
var url2='http://php.weather.sina.com.cn/search.php?city='
window.status='搜寻中...'; //隐藏状态栏信息
var a=document.form.city.selectedIndex;
var city1=document.form.city.options[a].value;
document.form.url.value=url2+city1;
//window.location=url+city1;
document.form.submit();
}
-->
</script>
<body>
<center>
<iframe width="300" height="70" name="frame" src="get_tianqi.php" frameborder="1"></iframe>
<form action="get_tianqi.php" method="post" name="form" target="frame">
<select name="city" onchange="go()">
<option value="">请选择一个城市</option>
<option value="广州">广州</option>
<option value="肇庆">肇庆</option>
<option value="湛江">湛江</option>
<option value="深圳">深圳</option>
<option value="东莞">东莞</option>
<input type="hidden" name="url" value="">
</select>
</form>
</center></body></html>

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.="<br>";
}
}
echo $e;
ob_end_flush();
?>  

你可能感兴趣的:(PHP)