1. 程式人生 > >php 實現http get和post(提交json資料)請求

php 實現http get和post(提交json資料)請求

 介面,抓取資料經常用到

//$arr為提交的資料為json型別   預設 get

function http_curl($url,$type='get',$res='json',$arr=''){
        //1.初始化curl
        $ch = curl_init();
        //2.設定curl的引數
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if($type == 'post'){
            curl_setopt($ch, CURLOPT_POST,1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //3.採集
        $output = curl_exec($ch);
        //4.關閉
        curl_close($ch);
        if($res=='json'){
            if(curl_error($ch)){
                //請求失敗,返回錯誤資訊
                return curl_error($ch);
            }else{
                //請求成功,返回資訊
                return json_decode($output,true);
            }
        }
    }