PHP请求远程API的CURL方法

API接口越来越多。PHP如何请求远程API呢?

记录以方便以后使用。

/**
 * 用于请求接口获取数据
 * @param $url          请求api网址
 * @param array $post    post数据
 * @return json          请求结果
 */
function get_by_curl($url,$post = false){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if($post){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

在Thinkphp中使用方法:放到common.php中。在控制器中直接

$result = $this->get_by_curl();引用。

You May Also Like

About the Author: 萌新

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注