How to send JSON string via POST in PHP
Some modern web services and APIs that requires API consumers to send JSON via a POST request. Here’s how you would program to do such task.
//API Url $url = 'http://apiprovider.com/api/v1/authentication/create'; //Initiate cURL. $ch = curl_init($url); //This array will be encoded to JSON data before sending. $jsonData = array( 'username' => 'SomeUsername', 'password' => 'SomePassword' ); //Encode the array to 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);
Once we’ve got the response from the API Provider, we can decode the JSON back to an array using json_decode() function, so that PHP can process or display to client easily.