When working with APIs, it’s common to send and receive data in JSON format. In PHP, you can use the cURL library to send HTTP requests, including sending JSON data in a POST request. In this article, we’ll show you how to POST JSON data with PHP cURL in a step-by-step guide.
Step 1: Set the URL and JSON data
The first step is to set the URL that you want to send the request to and the JSON data that you want to send in the request body. For this example, we’ll use a sample JSON data:
In this example, we’ve created an array of data and encoded it into a JSON string using the
Step 2: Set the cURL options
The next step is to set the cURL options for the request, including the URL, request method, and request body. Here’s an example of how to set the cURL options:
In this example, we’ve set the following options:
- CURLOPT_RETURNTRANSFER: Set to true to return the response as a string instead of outputting it directly to the screen.
- CURLOPT_CUSTOMREQUEST: Set to “POST” to specify that we’re sending a POST request.
- CURLOPT_POSTFIELDS: Set to the JSON data that we want to send in the request body.
- CURLOPT_HTTPHEADER: Set to an array of headers, including the Content-Type header to specify that we’re sending JSON data, and the Content-Length header to specify the length of the JSON data.
Step 3: Send the request and handle the response
The final step is to send the request using the
curl_exec() function and handle the response. Here’s an example of how to do this:
In this example, we’ve used the
curl_exec() function to send the request and store the response in the $response variable. We’ve also checked for any errors using the
curl_errno() function and displayed the error message if there was an error. Finally, we’ve closed the cURL handle using the
Step 4: Complete PHP Script
After combining the above code, you will get a full functional PHP script that can POST JSON data to remote APIs.
Save the file content and run this via the PHP command line interface.
In this article, we’ve shown you how to POST JSON data with PHP cURL in a step-by-step guide. By setting the URL and JSON data, setting the cURL options, and sending the request, and handling the response, you can easily send JSON data in a POST request using PHP cURL.