Sending POST data to an API in PHP
Had a fairly eventful day building an API teamed with a bespoke Codeigniter-driven content management system, and fell into a few problems when POST’ing information from the CMS to my web service.
I’ve put together a quick + dirty function that’ll get you started, and I’ll publish a more in-depth post later, with a dedicated Codeigniter library.
$url = 'http://webservice.local/data.json';
$data = array("name" => "Gareth", "email" => "gareth@mail.com");
$response = sendPostData($url, $data);
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));
return curl_exec($ch);
}
The JSON encoded string should be stored in $response. Use json_decode() to convert it into a usable StdClass object.