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

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

一、CURL操作

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

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

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

php 复制代码
/**
 * @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);
}

二、调用示例

php 复制代码
$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));
相关推荐
JaguarJack1 天前
FrankenPHP 原生支持 Windows 了
后端·php·服务端
BingoGo1 天前
FrankenPHP 原生支持 Windows 了
后端·php
JaguarJack2 天前
PHP 的异步编程 该怎么选择
后端·php·服务端
BingoGo2 天前
PHP 的异步编程 该怎么选择
后端·php
JaguarJack3 天前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay4 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954484 天前
CTF 伪协议
php
BingoGo6 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack6 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo7 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php