字符串不能解析为XML

时间:2013-12-06 09:15:14

标签: php xml

这是用于获取IP位置查询。

final class ipinfodb{
protected $errors = array();
protected $showTimezone = false;
protected $service = 'api.ipinfodb.com';
protected $version = 'v3';
protected $apiKey = '';

public function __construct(){}

public function __destruct(){}

public function setKey($key){
    if(!empty($key)) $this->apiKey = $key;
}

public function showTimezone(){
    $this->showTimezone = true;
}

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

public function getGeoLocation($host){
    $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 . '/' . 'ip_query.php?key=' . $this->apiKey . '&ip=' . $ip);

        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;
}
 }

这是用于获取位置查询。这里没有显示任何结果。如果我回显错误,则会出现以下错误

 $ipinfodb = new ipinfodb;
    $ipinfodb->setKey(IP_LOOKUP_KEY);
     if(isset($_GET['ip']))
     {
     $ip=$_GET['ip'];
     }
    //Get errors and locations
    $locations = $ipinfodb->getGeoLocation($ip);
    $errors = $ipinfodb->getError();



echo $errors;

结果显示:

  

无法将字符串解析为XML。   如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为你应该试试这个

    $xml = @file_get_contents('http://' . $this->service . '/' . $this->version . '/ip-city/' . '?key=' . $this->apiKey . '&ip=' . $ip . '&format=xml');