2012-05-10 70 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

感謝您的提示馬修! –