PHP下使用CURL方式POST数据至API接口的方法

来源:互联网 发布:最新全国高校数据库 编辑:程序博客网 时间:2024/06/05 06:46

PHP下使用curl方式post数据至api接口的方法

大部分的API的HTTP请求方式都为GET,所以不管用AJAX和PHP二次处理都能拿到返回的数据

但是一些API的HTTP请求方式是POST,那么我们就需要使用到curl了

其实,也比较简单,上代码:

view source
print?
01<?php    
02      
03    $url 'http://127.0.0.1/test.php';//POST指向的链接    
04    $data array(    
05        'access_token'=>'thekeyvalue'    
06    );    
07      
08    $json_data = postData($url$data);    
09    $array = json_decode($json_data,true);    
10    echo '<pre>';print_r($array);    
11          
12    function postData($url$data)    
13    {    
14        $ch = curl_init();    
15        $timeout = 300;     
16        curl_setopt($ch, CURLOPT_URL, $url);   
17        curl_setopt($ch, CURLOPT_REFERER, "http://www.jincon.com/");   //构造来路  
18        curl_setopt($ch, CURLOPT_POST, true);    
19        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
20        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
21        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);    
22        $handles = curl_exec($ch);    
23        curl_close($ch);    
24        return $handles;    
25    }    
26      
27?>  
1 0