[php] POST request with JSON body

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..."
}

This question is related to php json post

The answer is


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>

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

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...


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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time