首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

PHP的CURL步骤curl_setopt()函数案例介绍(抓取网页,POST数据)

2012-10-19 
PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)通过curl_setopt()函数可以方便快捷的抓取网

PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)

     通过curl_setopt()函数可以方便快捷的抓取网页(采集很方便PHP的CURL步骤curl_setopt()函数案例介绍(抓取网页,POST数据)),curl_setopt 是php的一个扩展库

     使用条件:需要在php.ini 中配置开启。(PHP 4 >= 4.0.2)
       //取消下面的注释
extension=php_curl.dll

      在Linux下面,需要重新编译PHP了,编译时,你需要打开编译参数——在configure命令上加上“–with-curl” 参数。

1、 一个抓取网页的简单案例:

   

/** * Make an HTTP request * * @return string API results * @ignore */function http($url, $method, $postfields = NULL, $headers = array()) {$this->http_info = array();$ci = curl_init();/* Curl settings */curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);//让cURL自己判断使用哪个版本curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);//在HTTP请求中包含一个"User-Agent: "头的字符串。curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);//在发起连接前等待的时间,如果设置为0,则无限等待curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);//设置cURL允许执行的最长秒数curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);//返回原生的(Raw)输出curl_setopt($ci, CURLOPT_ENCODING, "");//HTTP请求头中"Accept-Encoding: "的值。支持的编码有"identity","deflate"和"gzip"。如果为空字符串"",请求头会发送所有支持的编码类型。curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);//禁用后cURL将终止从服务端进行验证curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));//第一个是cURL的资源句柄,第二个是输出的header数据curl_setopt($ci, CURLOPT_HEADER, FALSE);//启用时会将头文件的信息作为数据流输出switch ($method) {case 'POST':curl_setopt($ci, CURLOPT_POST, TRUE);if (!empty($postfields)) {curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);$this->postdata = $postfields;}break;case 'DELETE':curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');if (!empty($postfields)) {$url = "{$url}?{$postfields}";}}if ( isset($this->access_token) && $this->access_token )$headers[] = "Authorization: OAuth2 ".$this->access_token;$headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];curl_setopt($ci, CURLOPT_URL, $url );curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );$response = curl_exec($ci);$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);$this->http_info = array_merge($this->http_info, curl_getinfo($ci));$this->url = $url;if ($this->debug) {echo "=====post data======\r\n";var_dump($postfields);echo '=====info====='."\r\n";print_r( curl_getinfo($ci) );echo '=====$response====='."\r\n";print_r( $response );}curl_close ($ci);return $response;}


更详细的参数说明参考:http://cn2.php.net/curl_setopt

热点排行