1、demo,抓取百度頁碼代碼:html
$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);
2、curl函數介紹:json
一、curl_init($url):初始化curl回話,返回資源類型curl
二、curl_setopt($ch, $option, $value):爲curl設置相應的常量,$ch爲curl_init()返回的資源句柄函數
三、curl_setopt_array($ch, $options):批量設置常量ui
四、curl_error($ch):返回當前會話最後一次錯誤的字符串this
五、curl_exec($ch):執行curl會話url
六、curl_getinfo($ch):獲取一個curl鏈接資源句柄信息spa
七、curl_close:關閉curl會話code
3、curl預約義常量htm
一、CURLOPT_HEADER:將頭文件的信息做爲數據流輸出
4、案例:
方法:
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); }