`
student_lp
  • 浏览: 428667 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

php工具类之【ip转换为对应地区地址类】

阅读更多
**
 * ip转换为对应地区地址类
 * @version 1.0 2012-12-20
 */
class ip2Area{
    protected $errors = array();
    protected $service = 'api.ipinfodb.com';
    protected $version = '***';
    protected $apiKey = '*******';
 
    public function __construct(){}
 
    public function __destruct(){}
 
    public function setKey($key){
        if(!empty($key)){
        	$this->apiKey = $key;	
        }
    }
 
    public function getError(){
        return implode("\n", $this->errors);
    }
 
    public function getCountry($host){
        return $this->getResult($host, 'ip-country');
    }
 
    public function getCity($host){
        return $this->getResult($host, 'ip-city');
    }
 
    private function getResult($host, $name){
        $ip = @gethostbyname($host);
 
        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}$/', $ip)){
            $xml = @file_get_contents('http://' . $this->service . '/' . $this->version . '/' . $name . '/?key=' . $this->apiKey . '&ip=' . $ip . '&format=xml');
            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[] = '"' . $host . '" is not a valid IP address or hostname.';
        return;
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics