In this guide, we are going to show you how to send JSON data in PHP.
In certain cases, you will come across web services and APIs that will require you to send JSON via a POST request.
The easiest way to achieve this is by using PHP’s cURL functions.
Take a look at the following example.
//The URL of the API. $url = 'http://example.com/api/JSON/create'; //Initiate cURL. $ch = curl_init($url); //The JSON data. $jsonData = array( 'username' => 'MyUsername', 'password' => 'MyPassword' ); //Encode the array into JSON. $jsonDataEncoded = json_encode($jsonData); //Tell cURL that we want to send a POST request. curl_setopt($ch, CURLOPT_POST, 1); //Attach our encoded JSON string to the POST fields. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); //Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //Execute the request $result = curl_exec($ch);
In the code above, we did the following.
- We specified the URL that we want to send our JSON to. This is usually the URL of the API that we want to send the data to.
- After that, we initiated cURL by using the curl_init function.
- Then, we setup a PHP array containing sample data.
- We encoded our PHP array into a JSON string by using the function json_encode.
- We when told cURL that we want to send a POST request by setting the CURLOPT_POST option to 1.
- After that, we attached our JSON data by using the CURLOPT_POSTFIELDS option.
- We then set the content-type of our request to application/json using the CURLOPT_HTTPHEADER option. It is extremely important to note that you should always use “application/json”, not “text/json”. Simply put, using “text/json” is incorrect and may lead to errors!
- Finally, we use the function curl_exec to execute our POST request. If you want to check for errors at this stage, then you should check out our article on error handling with cURL.
As you can see, it’s not much different than sending a regular POST request. In fact, the only real difference is that we set the content type to application/json.