您的当前位置:首页>全部文章>文章详情

php中的curl方法封装,解决返回数据乱码问题

发表于:2019-07-31 15:12:39浏览:62次TAG:
### curl方法封装 ```php /** * url = "http://xxx" * method = "GET | POST" * params = array("id" => 1) * cookie = 'string' * header = array('Accept:application/json', "User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"); */ function request($url, $method = 'GET', $params = array(), $cookie = '', $header = array()) { if (!function_exists('curl_init')) exit('curl_init function could not be found..'); if (empty($url)) exit('url should not be empty..'); $method = strtoupper($method) == 'GET' ? 'GET' : 'POST'; $ci = curl_init(); if(!empty($cookie)) { curl_setopt($ci, CURLOPT_COOKIE, $cookie); } // curl_setopt($ci, CURLOPT_USERAGENT, ''); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ci, CURLOPT_TIMEOUT, 30); curl_setopt($ci, CURLOPT_RETURNTRANSFER, true); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ci, CURLOPT_HEADER, false); if(count($header) > 0) { curl_setopt($ci, CURLOPT_HTTPHEADER,$header); } switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, TRUE); if (!empty($params)) { //echo http_build_query($params);exit; curl_setopt($ci, CURLOPT_POSTFIELDS, http_build_query($params)); } break; case 'GET': default : if (!empty($params)) { $url .= (strpos($url, '?') === false ? '?' : '&') . (is_array($params) ? http_build_query($params) : $params); } break; } curl_setopt($ci, CURLOPT_URL, $url); $response = curl_exec($ci); curl_close($ci); return $response; } ``` ### 如果返回的数据出现乱码 1. 检查头部信息 返回的是 gzip, deflate 数据, 添加如下代码 ``` // 设置头部 curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate')); // 这个是解释gzip内容................. curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate'); ``` 2. 其他
栏目分类全部>
腾讯云采购季云服务器一折促销