2013-06-04 290 views
57

我想通過PHP添加post to a Blogger blog。 Google提供了下面的示例。如何使用PHP?JSON體POST請求

You can add a post for a blog by sending a POST request to the post collection URI with a post JSON body:

POST https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/ 
Authorization: /* OAuth 2.0 token here */ 
Content-Type: application/json 

{ 
    "kind": "blogger#post", 
    "blog": { 
    "id": "8070105920543249955" 
    }, 
    "title": "A new post", 
    "content": "With <b>exciting</b> content..." 
} 
+1

[使用PHP發送JSON後(http://stackoverflow.com/questions/6213509/send-json-post-using-php) – freejosh

+0

我的可能重複也會建議爲你的內容使用JSON,因爲你可以創建一個類或函數來返回一個可以用json_encode序列化的對象。有關該主題的更多信息,請訪問:http://www.php.net/manual/de/ref.json.php - 這只是對此主題的其他建議:-) –

回答

98

您需要使用cURL library發送此請求。

<?php 
// Your ID and token 
$blogID = '8070105920543249955'; 
$authToken = 'OAuth 2.0 token here'; 

// The data to send to the API 
$postData = array(
    'kind' => 'blogger#post', 
    'blog' => array('id' => $blogID), 
    'title' => 'A new post', 
    'content' => 'With <b>exciting</b> content...' 
); 

// Setup cURL 
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/'); 
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE, 
    CURLOPT_RETURNTRANSFER => TRUE, 
    CURLOPT_HTTPHEADER => array(
     'Authorization: '.$authToken, 
     'Content-Type: application/json' 
    ), 
    CURLOPT_POSTFIELDS => json_encode($postData) 
)); 

// Send the request 
$response = curl_exec($ch); 

// Check for errors 
if($response === FALSE){ 
    die(curl_error($ch)); 
} 

// Decode the response 
$responseData = json_decode($response, TRUE); 

// Print the date from the response 
echo $responseData['published']; 

如果由於某種原因,你不能/不想使用捲曲,你可以這樣做:

<?php 
// Your ID and token 
$blogID = '8070105920543249955'; 
$authToken = 'OAuth 2.0 token here'; 

// The data to send to the API 
$postData = array(
    'kind' => 'blogger#post', 
    'blog' => array('id' => $blogID), 
    'title' => 'A new post', 
    'content' => 'With <b>exciting</b> content...' 
); 

// Create the context for the request 
$context = stream_context_create(array(
    'http' => array(
     // http://www.php.net/manual/en/context.http.php 
     'method' => 'POST', 
     'header' => "Authorization: {$authToken}\r\n". 
      "Content-Type: application/json\r\n", 
     'content' => json_encode($postData) 
    ) 
)); 

// Send the request 
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context); 

// Check for errors 
if($response === FALSE){ 
    die('Error'); 
} 

// Decode the response 
$responseData = json_decode($response, TRUE); 

// Print the date from the response 
echo $responseData['published']; 
+3

偉大的教程!甚至包括json部分:-) –

+0

@DustinKlein:謝謝!我嘗試了我的最佳狀態:-) –

+0

我收到錯誤**未能打開流:HTTP請求失敗**爲此「純」PHP示例://發送請求 $ response = file_get_contents(' https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/',FALSE,$ context);'如何解決它? – Matt

8

我覺得cURL將是一個很好的解決方案。這不是測試,但你可以嘗試這樣的:

$body = '{ 
    "kind": "blogger#post", 
    "blog": { 
    "id": "8070105920543249955" 
    }, 
    "title": "A new post", 
    "content": "With <b>exciting</b> content..." 
}'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here")); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $body); 
$result = curl_exec($ch); 
+0

我不認爲'CURLOPT_USERPWD '和'CURLAUTH_BASIC'會在'Authorization'頭部正確發送OAuth令牌。 –

+0

我不確定令牌的外觀。 'CURLOPT_USERPWD'的格式是'username:password'。這就是'Authorization'頭文件的內容,所以它應該和添加一個手動頭'Authorization:OAuth 2.0 token的base64 here'一樣的結果。 – MaX

+0

嘗試了代碼,我得到這個錯誤:'警告:curl_setopt()期望參數1是資源,null給'該令牌看起來像這樣btw:'ya29.AHES6ZTIXVmG56O1SWM9IZpTUIQCUFQ9C2AQdp8AgHL6emMN'我需要改變什麼參數? – Matt

0
<?php 
// Example API call 
$data = array(array (
    "REGION" => "MUMBAI", 
    "LOCATION" => "NA", 
    "STORE" => "AMAZON")); 
// json encode data 
$authToken = "xxxxxxxxxx"; 
$data_string = json_encode($data); 
// set up the curl resource 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/json',  
    'Content-Length: ' . strlen($data_string) , 
    'API-TOKEN-KEY:'.$authToken)); // API-TOKEN-KEY is keyword so change according to ur key word. like authorization 
// execute the request 
$output = curl_exec($ch); 
//echo $output; 
// Check for errors 
if($output === FALSE){ 
    die(curl_error($ch)); 
} 
echo($output) . PHP_EOL; 
// close curl resource to free up system resources 
curl_close($ch); 
1

我做了API通過網站上的形式發送數據以@Rocket Hazmat,@ dbau和@maraca代碼爲基礎的prosperworks。 我希望,這將幫助別人:

<?php 

if(isset($_POST['submit'])) { 
    //form's fields name: 
    $name = $_POST['nameField']; 
    $email = $_POST['emailField']; 

    //API url: 
    $url = 'https://api.prosperworks.com/developer_api/v1/leads'; 

    //JSON data(not exact, but will be compiled to JSON) file: 
    //add as many data as you need (according to prosperworks doc): 
    $data = array(
          'name' => $name, 
          'email' => array('email' => $email) 
         ); 

    //sending request (according to prosperworks documentation): 
    // use key 'http' even if you send the request to https://... 
    $options = array(
     'http' => array(
      'header' => "Content-Type: application/json\r\n". 
      "X-PW-AccessToken: YOUR_TOKEN_HERE\r\n". 
      "X-PW-Application:developer_api\r\n". 
      "X-PW-UserEmail: YOUR_EMAIL_HERE\r\n", 
      'method' => 'POST', 
      'content' => json_encode($data) 
     ) 
    ); 

    //engine: 
    $context = stream_context_create($options); 
    $result = file_get_contents($url, false, $context); 
    if ($result === FALSE) { /* Handle error */ } 
    //compiling to JSON (as wrote above): 
    $resultData = json_decode($result, TRUE); 
    //display what was sent: 
    echo '<h2>Sent: </h2>'; 
    echo $resultData['published']; 
    //dump var: 
    var_dump($result); 

} 
?> 
<html> 
    <head> 
    </head> 

    <body> 

     <form action="" method="POST"> 
      <h1><?php echo $msg; ?></h1> 
      Name: <input type="text" name="nameField"/> 
      <br> 
      Email: <input type="text" name="emailField"/> 
      <input type="submit" name="submit" value="Send"/> 
     </form> 

    </body> 
</html>