<?php
/*
	The API returns the location of an IP address 
	(country, region, city, zipcode, latitude, longitude) 
	and the associated timezone in XML format.
	Ref - http://ipinfodb.com/ip_location_api.php
 */
class Ipinfodb {
	###################### IP BASED CITY  ############################
	protected $errors 	= array();
	protected $service 	= 'api.ipinfodb.com';
	protected $version 	= 'v3';
	protected $apiKey 	= '';	
	public function __construct($apiKey)
	{
		$this->apiKey=$apiKey;
	}
	public function setKey($key){
		if(!empty($key)) $this->apiKey = $key;
	}

	public function getError(){
		return implode("\n", $this->errors);
	}

	public function getCountry($hostIP){
		return $this->getResult($hostIP, 'ip-country');
	}

	public function getCity($hostIP){
		return $this->getResult($hostIP, 'ip-city');
	}

	private function getResult($hostIP, $name) {
		if(preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $hostIP)) {		
			$url = 'http://' . $this->service . '/' . $this->version . '/' . $name . '/?key=' . $this->apiKey . '&ip=' . $hostIP . '&format=xml';
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT,1);
			$xml = curl_exec($ch);
			try {
				$response = @new SimpleXMLElement($xml);
				foreach($response as $field=>$value) {
					$result[(string)$field] = (string)$value;
				}
				return $result;
			}
			catch(Exception $e) {
				$this->errors[] = $e->getMessage();
				return;
			}
		}
		$this->errors[] = '"' . $hostIP . '" is not a valid IP address or hostname.';
		return;
	}	
}