General API interface with CURL: A simple way to access most APIs — use as is or extend as necessary
Since you likely interface with a lot of external APIs, there’s no need to keep rewriting the same tool. Just copy this and use the “apiBaseController” class as you need it. It’s a good, clean way to start any API accessing project!
<?php /** * Class apiBaseController * * Any access of APIs outside of Symfony can be extended from this class * * */ class apiBaseController { public $showDebug=false; // Whether debug message showing verbose response is on or not function apiCurlRequest($method = 'POST', $url, $headerArr=array(), $postFields = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); if ($method != 'POST' && !empty($method)) { // $headerArr[] = 'X-HTTP-Method-Override: ' . $method; } // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if(count(@$headerArr)>0) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); } if ($method=='POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); } if($method=='GET') { curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HTTPGET, 1); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $curl_response = curl_exec($ch); if($this->showDebug){ echo "<p>API RESPONSE: " . __FUNCTION__ . ": Method: $method; Url: $url; " . print_r($curl_response, true) . ";</p>"; } curl_close($ch); return $curl_response; } function buildApiHeaders($postString){ $headers = array( "Content-type: text/xml;charset=utf-8", "Content-length: ".strlen($postString), ); return $headers; } }