2012-05-10 71 views
0

我正在尝试使用Github v3 API并发布JSON来更新配置文件(或其他调用)并从Github获得以下响应;Github API v3与PHP POST

Array 
(
    [message] => Body should be a JSON Hash 
) 

我已经在相关页面上的API文档:http://developer.github.com/v3/users/

,而这个页面:http://developer.github.com/v3/#http-verbs覆盖POST/PATCH

下面是我使用

代码
$data = array("bio" => "This is my bio"); 
$data_string = json_encode($data); 

function curl($url) { 
    $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,1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,1); 
    curl_setopt($ch, CURLOPT_USERPWD, "USERNAME:PASSWORD"); 
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
    $content = curl_exec($ch); 
    curl_close($ch); 
    return $content; 
} 

$result = json_decode(curl('https://api.github.com/user'),true); 

我也试过CURLOPT_CUSTOMREQUEST作为'POST''PATCH',但得到了相同的错误响应两者。

任何人都可以指引我将数据发布到API的正确方向吗?

回答

1

您必须要么global $data_string要么将​​$data_string变量传递给curl()以获得可重用性。

例子:

function curl($curl, $data) 
{ 
    $data_string = json_encode($data); 
    // your code here 
} 
+0

哇...我怎么会过目那!谢谢。 –

0

您应该指定这样的标题:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
+0

感谢您的提示马修! –