用curl模拟http请求获取网页

用curl模拟http请求获取网页 http://news.baidu.com/ 的内容 ,然后分析打印这个网页里面的所有链接地址

<?php

/**
** 
** @author:hyb([email protected])
** @date:2014.05.19
**/

function getNews(){

$url = 'http://news.baidu.com/';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);//需要获取的URL地址
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);//启用时会将头文件的信息作为数据流输出

//获取文件流
$re = curl_exec($ch);
//关闭curl
curl_close($ch);

//转码为utf-8
if($re === FALSE){ //无结果
	$result = null;
	return $result;
	}else{ 
		if(json_encode($re) == 'null'){//如果编码不是utf8,则会返回null
			$res = iconv('GB2312','UTF-8//IGNORE',$re);
		}else{
			$res = $re;
	}
}

//正则获取超链
$str = '#<a.*?href="(http://.*?)".*?>(.*?)</a>#is';
preg_match_all($str,$res,$href);
if(!isset($href [1] )||!isset($href [2] )){
	return $result = null;
}else{
	$all_href = count($href[1]);
	for($i=0;$i< $all_href;$i++){
		$result[$i]['href'] = $href [1] [$i];
		if(empty($href [2] [$i])){
			$result[$i]['name'] = 'default';
		}else{
			$result[$i]['name'] = $href [2] [$i];
		}
	}
}
echo '  共有<font color="red">'.count($href [1] ).'</font>条超链:<br/>';
foreach($result as $k=>$v){
	echo '第'.$k.'条==><a href ='.$v['href'].' target="_blank">'.$v['name'].'-----------('.$v['href'].')</a><br/>';
}
return $result;
}

/**test**/
getNews();
/**tese**/

?>


你可能感兴趣的:(用curl模拟http请求获取网页)