我想通过PHP 在Blogger博客中添加帖子。Google提供了以下示例。如何在PHP中使用它?
您可以通过向带有帖子JSON正文的帖子集合URI发送POST请求来为博客添加帖子:
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..." }
您需要使用cURL库发送此请求。
<?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'];
如果由于某种原因您不想/不想使用cURL,可以这样做:
<?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'];