Tuesday, January 06, 2015

How to do CURL by POSTing JSON data

This is already documented on PHP Manual, however very recently I had to do a CURL with some data JSON encoded and POSTed to a WebService to get some results. The corresponding PHP coding is not very difficult, I am showing it below.  

I am testing this in localhost and it is going to run perfectly. I have a file called test.php and I will be calling the same file ( other file is okay too ) with a parameter "curl=1" during the curl process. 

<?php

// The CURL handler
if( isset($_REQUEST['curl']) && $_REQUEST['curl'] == 1)
{
  // The below echo will be the CURL result
  echo print_r
         json_decode
           file_get_contents( "php://input" )
         ),1);
  exit;

}

// CURL URL
$curl_url = "http://127.0.0.1/test.php?curl=1";

// Data we are going to Submit/POST
$base_data = array( 
             "page" => 5,
             "showList" => "customer",
            "sortBy" => "salary",
            "orderBy" => "desc",
            "includePriceGroups" => true,
          "countryCode" => "US",
            "languageCode" =>"EN" );

// JSON Encoding the POST data
$post_data = json_encode( $base_data );

// CURL Process Init
$ch = curl_init( $curl_url );

// SET CURL Options
// Set the method to 'POST'
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
// Set the DATA
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);   

// GET The result as a string                                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
// SET the HEADER
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                         
    "Content-Type: application/json",                               
    "Content-Length: " . strlen($post_data))                         );                                                                                                                 
// GET the Result 
$result = curl_exec($ch);

// Show Result
echo "This Result:: " . $result;
?>

Though I have entered the "Content-type" header to be "application/json", but it can be "text/plain" also.


In the above scenario, this is what we get as output : 


stdClass Object
(
    [page] => 5
    [showList] => customer
    [sortBy] => salary
    [orderBy] => desc
    [includePriceGroups] => 1
    [countryCode] => US
    [languageCode] => EN
)


Now, let's find out, why the output is like that.  We are posting a data like this :


{ "page":5,"showList":"customer","sortBy":"salary", 
  "orderBy":"desc", "includePriceGroups":true, 
  "countryCode":"US", "languageCode":"EN"
}

It is in JS Object Notation format. We are getting the above data in CURL handler written at the top of the script : 

if( isset($_REQUEST['curl']) && $_REQUEST['curl'] == 1)
{
    echo print_r
         json_decode
           file_get_contents( "php://input" )
         ),1);
    exit;
}

We won't get this data in $_POST or $_REQUEST variables. To receive the post data, we need to call file_get_contents("php://input") i.e we are receiving it as an input stream. After that we convert it to a Object (of stdClass) by calling json_decode() function. Print_r() function finally print the object.

Hope this helps.

No comments: