Post Json Data With Php curl
September 10, 2018
How to POST JSON Data With PHP cURL?
The PHP cURL is a library used for making HTTP requests. use PHP cURL, we need to enabled libcurl module for PHP on your system. When we working with web services and APIs, sending JSON data via POST request is the most required functionality. PHP cURL makes it easy to POST JSON data to URL. I will show you how to POST JSON data using PHP cURL and get JSON data in PHP.
Below example makes an HTTP POST request and send the JSON data to URL with cURL in PHP.
$data = array("first_name" => "dayanand","last_name" => "saini","email"=>"firstname.lastname@example.org","website"=>'www.webtechsource.com' );
#encode php array in json
$post_json = json_encode( $data);
$ch = curl_init( $urls );
# Setup request to send json via POST.
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_json );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
Step by step explanation of the above code:
1 . the URL ($urls) where the JSON data need to be sent.
2. Initiate new cURL resource using curl_init().
3. Setup data in PHP array and encode into a JSON string using json_encode().
4. Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option. Get post method in php
5. Set the Content-Type of request to application/json using CURLOPT_HTTPHEADER option.
6. Return response as a string instead of outputting it using CURLOPT_RETURNTRANSFER option.
7. Finally, curl_exec() function is used to execute the POST request
Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report.