Rumah > pembangunan bahagian belakang > tutorial php > php函数fsockopen获取新浪天气预报

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

巴扎黑
Lepaskan: 2016-11-24 14:48:40
asal
1147 orang telah melayarinya

取得新浪天气预报网页的城市当日信息. 
共有两个文件: 
tianqi.html:利用下拉菜单跳转到网页获得天气预报信息,返回信息到浮动帧内; 
 

 
<script> <br><!-- <br/>function go(){ <br/>var url2=&#39;http://php.weather.sina.com.cn/search.php?city=&#39; <br/>window.status=&#39;搜寻中...&#39;; //隐藏状态栏信息 <br/>var a=document.form.city.selectedIndex; <br/>var city1=document.form.city.options[a].value; <br/>document.form.url.value=url2+city1; <br/>//window.location=url+city1; <br/>document.form.submit(); <br/>} <br/>--> <br></script> 
 
 
 
 
 
 
 
 

get_tianqi.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,"");//取得天气预报的截取段 
$end=strpos($content,""); 
$len=$end-$start; 
$b=substr($content,$start,$len); //截取得指定内容 
//从上面的截取段中取得城市今日天气预报的截取段 
$sub_start=strpos($b,"
");  
$sub_end=strpos($b,"
"); 
$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(); 
?>  

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan