采集方式::【比较简单的两种模式】
一、采集页面curl模式
//生成一个curl对象
$curl=curl_init();
//设置URL和相应的选项
curl_setopt($curl, CURLOPT_URL, "http://www.youku.com/");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //将curl_exec()获取的信息以字符串返回,而不是直接输出。
//执行curl操作
$file=curl_exec($curl);
var_dump($file);
二、采集页面 file_get_contents() 模式
//使用file_get_contents()
$data=file_get_contents("http://www.youku.com");
var_dump($data);
三、采集网站指定内容
$url="http://www.sohu.com/";
$file = file_get_contents("compress.zlib://".$url);
$preg = '#<title>(.*)</title>#isU'; //正则表达式
preg_match($preg , $file ,$result);
print_r($result);
$url="http://www.sohu.com/";
$file = file_get_contents("compress.zlib://".$url);
$preg = '#<a data-clev=".*">(.*)</a>#isU'; //正则表达式
preg_match_all($preg , $file ,$result);
print_r($result);
注释:正则表达式 .* 代表任意数据;(.*)是要获取的数据。
四、采集网站图片保存到本地
$url="http://www.baidu.com/";
$file = file_get_contents("compress.zlib://".$url);
//$preg = '#<img src=".*">#isU'; //正则表达式1
$preg = '/<img.*?src="(.*?)".*?>/is'; //正则表达式2
preg_match($preg , $file ,$result);
//print_R($result);exit;
file_put_contents("baidu.png","http:".$result[0]);
采集内容乱码处理::【当内容无法正常获取的时候,分两种情况第一种是防盗链,第二种是页面需要解压】
1、需要解压时----页面收到压缩数据 浏览解压
compress.zlib:实现解压 进行转码即可
$url="http://www.sohu.com/";
echo file_get_contents("compress.zlib://".$url);
2、防盗链情况下解决办法,模拟浏览器
$url="http://www.sohu.com/";
ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)');
$html=file_get_contents($url);
//echo $html;
echo mb_convert_encoding($html,'utf8','gbk'); //转码