curl可以说是php里一个非常强大的功能,每个php程序员都应该学习并熟悉curl,使用curl前确保你的php_curl扩展已经开启。
一、curl使用
例如:我们采集深圳智联招聘上PHP招聘的第一页信息
$url='http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E6%B7%B1%E5%9C%B3&kw=php&sm=0&p=1';<BR>//初始化<BR>$ch = curl_init();<BR>//设置选项,包括URL<BR>curl_setopt($ch, CURLOPT_URL, $url);<BR>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不自动输出内容<BR>curl_setopt($ch, CURLOPT_HEADER, 0);//不返回头部信息<BR>//执行curl<BR>$output = curl_exec($ch);<BR>//错误提示<BR>if(curl_exec($ch) === false){<BR> die(curl_error($ch));<BR>}<BR>//释放curl句柄<BR>curl_close($ch);<BR>header('Content-type: text/html; charset=utf-8');<BR>echo $output;<BR>
当然我们必须对返回的数据使用<>处理,找出我们想要的那一部分,然后根据你的需要把数据填充到你网站里
//职位名称<BR>preg_match_all('/<td class="Jobname">.*?(.*?)<\/a>/s', $output, $title);<BR>$title[1];//链接<BR>$title[2];//标题<BR>//公司名称<BR>preg_match_all('/<td class="Companyname">.*?(.*?)<\/a>/s', $output, $company);<BR>$company[1];//链接<BR>$company[2];//名字<BR>//工作地点<BR>preg_match_all('/<td class="Companyaddress">\s*(.*?)\s*<\/td>/s', $output, $address);<BR>$address[1];//地点<BR>//发布日期<BR>preg_match_all('/<td class="releasetime">\s*(.*?)\s*<\/td>/s', $output, $time);<BR>$time[1];//时间<BR>var_dump($time[1]);<BR>
二、常用功能
curl的核心是通过设置各种选项来达到各种功能,这里我们介绍几种常用的选项。
1.post数据
$post=array(<BR>'uid'=>'test',<BR>'pwd'=>'curl123'<BR>);<BR>curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式<BR>curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));//POST数据<BR>
2.cookie
$savefile=dirname(__FILE__).'save.txt';<BR>$getfile=dirname(__FILE__).'get.txt';<BR>//可以分开使用<BR>curl_setopt($ch, CURLOPT_COOKIEJAR, $savefile); //保存 <BR>curl_setopt($ch, CURLOPT_COOKIEFILE, $getfile); //读取<BR>
3.伪造IP、来路
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8'));//构造IP <BR>curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com");//构造来路 <BR>
curl_setopt选项大全,详见PHP手册:http://www.php.net/manual/zh/function.curl-setopt.php
三、多线程
官方示例
// 创建一对cURL资源<BR>$ch1 = curl_init();<BR>$ch2 = curl_init();<BR>// 设置URL和相应的选项<BR>curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");<BR>curl_setopt($ch1, CURLOPT_HEADER, 0);<BR>curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");<BR>curl_setopt($ch2, CURLOPT_HEADER, 0);<BR>// 创建批处理cURL句柄<BR>$mh = curl_multi_init();<BR>// 增加2个句柄<BR>curl_multi_add_handle($mh,$ch1);<BR>curl_multi_add_handle($mh,$ch2);<BR>$running=null;<BR>// 执行批处理句柄<BR>do {<BR> usleep(10000);<BR> curl_multi_exec($mh,$running);<BR>} while ($running > 0);<BR>// 关闭全部句柄<BR>curl_multi_remove_handle($mh, $ch1);<BR>curl_multi_remove_han<div style="color:transparent">!本文来源gaodai.ma#com搞##代!^码网(</div><sup>搞gaodaima代码</sup>dle($mh, $ch2);<BR>curl_multi_close($mh);<BR>