【PHP】CURL请求第三方API接口

发布于:2025-08-03 ⋅ 阅读:(20) ⋅ 点赞:(0)

当我们需要调用第三方接口时,就需要使用CURL,通过CURL操作去请求第三方API接口,有的是通过POST方式,有的是通过GET方式,下面介绍一个通用的使用CURL调用API接口的方法。

一、CURL操作

共两个方法,分别是CURL操作、JSON转数组

 CURL操作:传入需要的参数,返回API接口的返回值

JSON转数组:一般接口返回的类型是json格式,为方便使用需要将json转换成数组格式

/**
 * @describe CURL操作,支持POST和GET两种请求方式
 * @param $url:API接口请求地址,$param:请求参数,$ispost:请求方式 post=1/get=2
 * @return array  接口返回结果集
 */
public function freeApiCurl($url,$params=false,$ispost=0){
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'free-api' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        return false;
    }
    curl_close( $ch );
    return $response;
}

/**
 * 将JSON内容转为数组,并返回
 */
public function returnArray($content){
    return json_decode($content,true);
}

二、调用示例

$key = 'xxxxxx';
$apiUrl = 'https://restapi.amap.com/v3/ip';
$params = [
        "key" => $key,
        "ip" => $ip,
    ];
$params = http_build_query($params);    //系统函数,组装参数,形如key=xxxxxxx&ip=123.6.49.12

////////// GET方式请求 ////////////
$result = $this->returnArray($this->freeApiCurl($apiUrl,$params));

////////// POST方式请求 ////////////
$result = $this->returnArray($this->freeApiCurl($apiUrl,$params,1));


网站公告

今日签到

点亮在社区的每一天
去签到