PHP 采集数据

采集方式::【比较简单的两种模式】

一、采集页面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');  //转码



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值