Tony Borcello
Tony Borcello

Reputation: 11

Post a JSON object from PHP using cUrl

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 ?

Upvotes: 0

Views: 6421

Answers (2)

Oyeme
Oyeme

Reputation: 11225

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

Upvotes: 2

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

urlencode() is the best method to post URL in coded form...

$json_output = json_encode($object_array, JSON_UNESCAPED_SLASHES);
$url = 'www.example.com?url='.urlencode($json_output);

And you will get your array after urldecode() of url parameter...

$json = urldecode($_GET['url']);

Upvotes: 0

Related Questions