Post Json Data With Php curl

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.

 

 

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.

I, Dayanand Saini,the founder and chief editor of www.webtechsource.com,have been working as a software engineer from last 4+ years. It's my hobby to learn new things and implement on live environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

− 4 = 4

%d bloggers like this: