一、demo,抓取百度页码代码:
$url = 'https://www.baidu.com/'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_TIMEOUT, 120); $html = curl_exec($ch); curl_close($ch); var_dump($html);
二、curl函数介绍:
1、curl_init($url):初始化curl回话,返回资源类型
2、curl_setopt($ch, $option, $value):为curl设置相应的常量,$ch为curl_init()返回的资源句柄
3、curl_setopt_array($ch, $options):批量设置常量
4、curl_error($ch):返回当前会话最后一次错误的字符串
5、curl_exec($ch):执行curl会话
6、curl_getinfo($ch):获取一个curl连接资源句柄信息
7、curl_close:关闭curl会话
三、curl预定义常量
1、CURLOPT_HEADER:将头文件的信息作为数据流输出
四、案例:
方法:
public function curlTool($url, $params = [], $header = [], $method = 'GET') { $opts = [ CURLOPT_TIMEOUT => 30, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_SSL_VERIFYHOST => FALSE, CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_HTTPHEADER => $header, CURLOPT_HEADER => FALSE, CURLOPT_PORT => 82 ]; switch (strtoupper($method)) { case 'GET' : $opts[CURLOPT_URL] = $url . '?' . http_build_query($params); $opts[CURLOPT_POST] = FALSE; break; case 'POST': $opts[CURLOPT_URL] = $url; $opts[CURLOPT_POST] = TRUE; $opts[CURLOPT_POSTFIELDS] = $params; break; } $ch = curl_init($url); curl_setopt_array($ch, $opts); $result = curl_exec($ch); $error = curl_error($ch); curl_close($ch); if ($error) { die('curl执行出错error:' . $error); } var_dump(json_decode($result)); }
调用:
public function test() { $url = 'url'; $header = [ 'test:test' ]; $params = [ 'test' => test ]; $this->curlTool($url, $params, $header); }