如何使用PHP和curl发布JSON?

时间:2013-07-05 13:34:28

标签: php curl

我设法使用以下设置让我的请求在“Advanced Rest Client”中工作:

enter image description here

但是,我尝试使用PHP重新创建相同的请求,但我无法弄清楚我做错了什么。这就是我所拥有的:

$config['key'] = "xxxxxxxxxxxx";
$config['clientid'] = xxxxxxxxx;

$url = 'http://xxxxxxxxxxxxxxxx.curdbee.com/invoices.json?api_token='.$config['key'];

$data = Array();  
$data['invoice']['client_id'] = $config['clientid'];

$data_string = json_encode($data);                                                                                   

$ch = curl_init($url);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);

echo curl_error($ch);

print_r($result);

$ result和curl_error都没有输出任何东西,我无法理解为什么。

2 个答案:

答案 0 :(得分:0)

我只需要添加这两行:

curl_setopt($ ch,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);

答案 1 :(得分:-1)

试试这个

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);