86

I would like to add a post to a Blogger blog via PHP. Google provided the example below. How to use that with PHP?

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..."
}
kero
  • 10,647
  • 5
  • 41
  • 51
Matt
  • 2,981
  • 5
  • 23
  • 33
  • 1
    possible duplicate of [Send json post using php](http://stackoverflow.com/questions/6213509/send-json-post-using-php) – freejosh Jun 04 '13 at 14:24
  • I would also recommend using JSON for your content, since you could create a class or function which will return an object you could serialize with json_encode. Further information on that topic you can find here: http://www.php.net/manual/de/ref.json.php - This is just an additional suggestion to this topic :-) – Dustin Klein Jun 04 '13 at 14:30
  • 1
    The `stream_context_create` `http` `content` field contains the http body for the request. Adding this comment b/c this was not explicitly stated in the answer. – toddmo May 13 '18 at 17:11

5 Answers5

152

You need to use the cURL library to send this request.

<?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);

// Close the cURL handler
curl_close($ch);

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

If, for some reason, you can't/don't want to use cURL, you can do this:

<?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'];
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • I'm receiving the error **failed to open stream: HTTP request failed** for the "pure" PHP example at this line: `// Send the request $response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);` How to fix it? – Matt Jun 04 '13 at 15:10
  • @Matt: Does the cURL example (first one) work? Your webhost/PHP installation could be blocking `file_get_contents`. Is there anymore to the error besides that? – gen_Eric Jun 04 '13 at 15:16
  • The cURL example works without an error but does not create a new post on the Blogger blog. There are no error messages - just an empty response. My token is valid and I double checked the blog ID. Any ideas? – Matt Jun 04 '13 at 16:11
  • Here is the complete error message: `Warning: file_get_contents(https://www.googleapis.com/blogger/v3/blogs/[blogid]/posts/) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized` – Matt Jun 04 '13 at 16:27
  • @Matt: How are you getting the token? Are you sure it's valid? – gen_Eric Jun 04 '13 at 18:34
  • 1
    I noticed that authorization header must constructed like this: `Authorization: OAuth {$authToken}`. – SIFE Nov 08 '13 at 11:21
  • what's the advantage of using CURL? – pppp Jun 19 '16 at 08:22
  • @user1930608: Nothing, really. cURL might make setting headers/options easier, but you can do everything without cURL. – gen_Eric Jun 20 '16 at 13:37
  • does we should close connection with curl_close($ch); after get result? – Saeed Arianmanesh Feb 23 '21 at 08:15
  • @SaeedArianmanesh Yes, you should use `curl_close()`. I'll add that to the example code :-) – gen_Eric Feb 23 '21 at 16:46
13

I think cURL would be a good solution. This is not tested, but you can try something like this:

$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);
MaX
  • 1,765
  • 13
  • 17
  • I don't think `CURLOPT_USERPWD` and `CURLAUTH_BASIC` will send the OAuth token correctly in the `Authorization` header. – gen_Eric Jun 04 '13 at 14:38
  • I'm not sure how the token looks. The format for `CURLOPT_USERPWD ` is `username:password`. This is what's put into the `Authorization` header, so it should be the same result as adding a manual header `Authorization: base64 of OAuth 2.0 token here`. – MaX Jun 04 '13 at 14:43
  • Tried the code and I'm getting this error: `Warning: curl_setopt() expects parameter 1 to be resource, null given` The token looks like this btw: `ya29.AHES6ZTIXVmG56O1SWM9IZpTUIQCUFQ9C2AQdp8AgHL6emMN` What parameter do I need to change? – Matt Jun 04 '13 at 15:14
  • Sorry, forgot to initialize curl. I've updated the script with `$ch = curl_init();`. – MaX Jun 04 '13 at 15:35
  • It's working now but Blogger sends this error: `Error: 401 HTTP Basic Authentication is not supported for this API` Is it because of `curl_setopt($ch, CURLOPT_USERPWD,"[token]);"`? – Matt Jun 04 '13 at 16:09
  • So far so good. No, it's probably because of `curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);`. Apparently they don't support basic authorization. Try changing it to `curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);` – MaX Jun 04 '13 at 16:14
  • Changed it and now I'm getting a new error from Blogger back: `"error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }` Any ideas? – Matt Jun 04 '13 at 16:24
  • Alright, try setting the Authorization header manually. I've updated the example. – MaX Jun 04 '13 at 16:45
  • Or, du you have a login that is not the token? – MaX Jun 04 '13 at 16:50
3

If you do not want to use CURL, you could find some examples on stackoverflow, just like this one here: How do I send a POST request with PHP?. I would recommend you watch a few tutorials on how to use GET and POST methods within PHP or just take a look at the php.net manual here: httprequest::send. You can find a lot of tutorials: HTTP POST from PHP, without cURL and so on...

Community
  • 1
  • 1
Dustin Klein
  • 319
  • 2
  • 9
3

I made API sending data via form on website to prosperworks based on @Rocket Hazmat, @dbau and @maraca code. I hope, it will help somebody:

<?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>
Tommy L
  • 140
  • 11
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);