curl可以说是php里一个非常强大的功能,每个php程序员都应该学习并熟悉curl,使用curl前确保你的php_curl扩展已经开启。
[b]
一、curl使用
[/b]例如:我们采集深圳智联招聘上PHP招聘的第一页信息
[url=(.*?)]$title[1];//链接
$title[2];//标题
//公司名称
preg_match_all('/<td class="Companyname">.*?<a href="(.*?)"\starget="_blank">(.*?)<\/a>/s', $output, $company);
$company[1];//链接
$company[2];//名字
//工作地点
preg_match_all('/<td class="Companyaddress">\s*(.*?)\s*<\/td>/s', $output, $address);
$address[1];//地点
//发布日期
preg_match_all('/<td class="releasetime">\s*(.*?)\s*<\/td>/s', $output, $time);
$time[1];//时间
var_dump($time[1]);
[b]
二、常用功能
[/b]curl的核心是通过设置各种选项来达到各种功能,这里我们介绍几种常用的选项。
[b]1.post数据
[/b]
$post=array(
'uid'=>'test',
'pwd'=>'curl123'
);
curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));//POST数据
[b]2.cookie
[/b]
[url=http://www.php.net/manual/zh/function.curl-setopt.php]http://www.php.net/manual/zh/function.curl-setopt.php
[/url][b]三、多线程
[/b]官方示例
// 创建一对cURL资源
$ch1 = curl_init();
$ch2 = curl_init();
// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);
// 创建批处理cURL句柄
$mh = curl_multi_init();
// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);
$running=null;
// 执行批处理句柄
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while ($running > 0);
// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);