Skip to content

Instantly share code, notes, and snippets.

@erikfrerejean
Last active December 18, 2015 03:58
Show Gist options
  • Save erikfrerejean/5721796 to your computer and use it in GitHub Desktop.
Save erikfrerejean/5721796 to your computer and use it in GitHub Desktop.
<?php
/**
* Class voor de communicatie met api.postcodeapi.nu
*/
class PostcodeAPI {
/**
* @var String API URI
*/
const API_URI = 'http://api.postcodeapi.nu';
/**
* @var String api key
*/
private $apiKey;
/**
* @var Array headers
*/
private $headers = array();
/**
* @var resource curl session
*/
private $curl;
/**
*/
private $response;
/**
* Construct API class
*
* @var String $apiKey Your API key
*/
public function __construct($apiKey) {
$this->apiKey = $apiKey;
$this->curl = curl_init();
$options = array(
);
foreach ($options as $option => $value) {
curl_setopt($this->curl, $option, $value);
}
}
/**
* Execute the request
*/
public function request($postcode, $huisnummer = false) {
// Add the authentication header
$this->_createAuthenticationHeaders();
// Prepare request
// Haal mogelijke spaties weg
$postcode = str_replace(array(' '), '', $postcode);
// Set URI
$uri = self::API_URI;
$uri .= (!empty($postcode)) ? '/' . $postcode : '';
$uri .= (!empty($huisnummer)) ? '/' . (int) $huisnummer : '';
curl_setopt($this->curl, CURLOPT_URL, $uri);
// Set all headers
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
// Request
$this->response = curl_exec($this->curl);
}
/**
* Create the authentication headers
*/
private function _createAuthenticationHeaders() {
$this->headers = array_merge($this->headers, array(
'Accept: */*',
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
'Accept-Language: en',
"Api-Key: {$this->apiKey}",
));
}
/**
* Get request result
*/
public function result($encoded = true) {
return ($encoded) ? $this->response : json_decode($this->response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment