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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | <?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; } } |