CURL模拟请求RESTAPI接口(基于PHP)

    //执行curl请求
    function restful_request($url,$data=[],$method='GET'){
        $method=strtoupper($method);
        $headerArray =["Content-type:application/json;"]
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if($method=='GET'){
            if(empty($data)==false&&is_array($data)){
                $queryString="";
                foreach($data as $param){
                    if($queryString=!""){
                        $queryString.='&';
                    }
                    $queryString.=$param;
                }
                $url.="?".$queryString;
                curl_setopt($ch, CURLOPT_URL,$url);
            }
            $headerArray[]=["Accept:application/json"];
        }else if($method=='POST'){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $headerArray[]=["Accept:application/json"];
        }else if(in_array($method,['PUT','DELETE','PATCH'])){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($url,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

 

转载于:https://my.oschina.net/u/1172593/blog/2934163

你可能感兴趣的:(php,json)