Viewed   76 times

I have created a JSON object using php functionality json_encode

The Object is formulated this way:

$object_array[]=array('value1' => $value1, 'value2' => $value2);

$json_output = json_encode($object_array, JSON_UNESCAPED_SLASHES);

I need to post the $json_output to a URL using the 'cUrl' functionality of PHP.

Can anyone suggest something based on the above code ?

 Answers

2

Post json objectusing curl.

$data = array('value1' => $value1, 'value2' => $value2);                                                                    
$data_string = json_encode($data);                                                                                   

$ch = curl_init('http://api.local/rest/users');   // where to post                                                                   
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);
Saturday, November 19, 2022
 
5

Well folks, I have figured this one out!

To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));

Monday, September 19, 2022
 
codesen
 
2

Without using any external dependency or library:

$options = array(
  'http' => array(
    'method'  => 'POST',
    'content' => json_encode( $data ),
    'header'=>  "Content-Type: application/jsonrn" .
                "Accept: application/jsonrn"
    )
);

$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

$response is an object. Properties can be accessed as usual, e.g. $response->...

where $data is the array contaning your data:

$data = array(
  'userID'      => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
  'itemKind'    => 0,
  'value'       => 1,
  'description' => 'Boa saudaÁ„o.',
  'itemID'      => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);

Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.

If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/

Saturday, October 8, 2022
4

The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:

$.ajax({
    url      : url,//note that this is setting the `url` property to the value of the `url` variable
    data     : {ID:$('#ddlClients').val()},
    type     : 'post',
    success  : function(Result){
            var myObj = $.parseJSON(Result);
            //you can now access data like this:
            //myObj.Address_1
        }
    }
  );

You can let jQuery do this for you by setting the dataType property for your AJAX call to json:

$.ajax({
    url      : url//note that this is setting the `url` property to the value of the `url` variable
    data     : {ID:$('#ddlClients').val()},
    dataType : 'json',
    type     : 'post',
    success  : function(Result){
            //you can now access data like this:
            //Result.Address_1
        }
    }
  );

The above examples expect that the response from the server to be in this format (from your question):

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
Tuesday, September 13, 2022
3

Here is an example using both libraries :

#include <stdio.h>
#include <curl/curl.h>
#include <json-c/json.h>

int  main(int argc, char **argv)
{

  /* LIB JSON-C PART */
    /* Create a JSON object */
    json_object * jObj = json_object_new_object();

    /* Create a string element */
    json_object *jString = json_object_new_string("Guybrush");

    /* Include the element to the JSON final object */
    json_object_object_add(jObj,"name", jString);


  /* LIB CURL PART */
    /* Initialize CURL */ 
    CURL *curlHandler = curl_easy_init();

    if(curlHandler) {
      /* Set CURL parameters */
      curl_easy_setopt(curlHandler, CURLOPT_URL, "http://api.yoururl.com");
      curl_easy_setopt(curlHandler, CURLOPT_CUSTOMREQUEST, "POST");
      curl_easy_setopt(curlHandler, CURLOPT_POSTFIELDS,  
                json_object_to_json_string(jObj));

      /* Perform the request */ 
      CURLcode res = curl_easy_perform(curlHandler);

      /* Check for errors */ 
      if(res != CURLE_OK)
        fprintf(stderr, "CURL failed: %sn",
                curl_easy_strerror(res));

      /* Clean up */ 
      curl_easy_cleanup(curlHandler);
      json_object_object_del(jObj, "name");
      free(jObj);
  }
  return 0;
}
Wednesday, November 30, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :