Sending JSON via POST in PHP

Sometimes, you’ll come across web services and APIs that will require you to send JSON via a POST request.

The code:

Step by step explanation of the above code:

  1. We setup the URL that we want to send our JSON to.
  2. We initiated cURL using curl_init.
  3. We setup a PHP array containing sample data.
  4. We encoded our PHP array into a JSON string by using the function json_encode.
  5. We specified that we were sending a POST request by setting the CURLOPT_POST option to 1.
  6. We attached our JSON data using the CURLOPT_POSTFIELDS option.
  7. We set the content-type of our request to application/json. It is extremely important to note that you should always use “application/json”, not “text/json”. Simply put, using “text/json” is incorrect!
  8. Finally, we used the function curl_exec to execute our POST request. If you want to check for errors at this stage, then you should check out my article on error handling with cURL.

As you can see, it’s not much different than sending a regular POST request. In fact, it’s actually pretty simple.

Related: How to retrieve raw JSON POST data with PHP.

Comments

comments