<?php
function get_url_content($Url,$Method = 'c') {
//引入需要的语言编码.如果没有, 就会默认为utf-8,不必担心.
global $Charset;
$Urlarr = parse_url($Url);
//如果检测不出域名,就返回.
if (!isset($Urlarr['host'])) {
return false;
}
//我们用智能方式定义header头倍信息.
foreach (@getallheaders() as $key => $val){
$key==='Host' && $val = $Urlarr['host'];
$key==='Referer' && $val ='http://'.$Urlarr['host'];
$str .= "'$key:$val', n";
}
//虚拟来路.
!eregi('Referer',$str) && $str .="'Referer:http://{$Urlarr['host']}', n";
//经过修正, 基本上, 来路也是那个站, 主机也是Url站点.
$Header = array(trim($str));
//下面仅仅是选择用哪个程序来采集.
if($Method === 'f'&&function_exists('file_get_contents')) {
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>$Header,
)
);
$cxContext = stream_context_create($opts);
$file_contents = @file_get_contents($Url, false, $cxContext);
} elseif ($Method === 'c'&&function_exists('curl_init')) {
$Ch = curl_init();
$Timeout = 5;
curl_setopt($Ch,CURLOPT_HTTPHEADER,$Header);
curl_setopt ($Ch, CURLOPT_URL, $Url);
curl_setopt ($Ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt ($Ch, CURLOPT_CONNECTTIMEOUT, $Timeout);
$file_contents = curl_exec($Ch);
curl_close($Ch);
}
//为了让样式显示得漂亮,我们给它加一句目标引向.
$file_contents = str_replace('</title>',"</title>n<base href="http://{$Urlarr['host']}/" />",$file_contents);
//处理最常见的几种编码, 如果目标网站没有编码, 就默认为GBK
!preg_match('/charset=([^<>"]*)"/isU',$file_contents,$lang) && $lang[1]='GBK';
function_exists('mb_convert_encoding') && $file_contents = mb_convert_encoding($file_contents,empty($Charset)?'UTF-8':$Charset,$lang[1]);
//注销部分代码;
unset($Url,$lang,$Timeout,$Urlarr,$Charset);
return $file_contents;
}
//测试开始 测试用file_get_contents方式
HEADER("CONTENT-TYPE:TEXT/HTML; CHARSET=UTF-8");
//http://www.xtzj.com/read-htm-tid-347550.html 这是采集不到.
$file = get_url_content("http://www.hao123.com",'f');
$file = strip_tags($file,'<a>');
preg_match_all('/(http:[^"<>]*)>/isU',$file,$link);unset($link[0]);
$link = $link[1];
//我们来模拟获得数据. 自己更换数字.0-151 下面是用curl方式
$x = 10;
$file = get_url_content($link[$x]);
echo $file;
?>
全部写上说明, 注释..
有不明白的回复.. 我来给采集普及一下知识.