simplexml_load_file警告错误

时间:2015-01-27 16:55:03

标签: php xml google-maps google-maps-api-3

我有一个简单的函数,可以使用Google提供的简单XML将地址字符串转换为经度和纬度。我偶尔会遇到这个奇怪的警告错误:

  

警告:   使用simplexml_load_file(http://maps.googleapis.com/maps/api/geocode/xml?address=&sensor=true):   无法打开流:HTTP请求失败! HTTP / 1.0 500内部   第193行/search_results.php中的服务器错误

     

警告:simplexml_load_file():I / O警告:无法加载外部   实体   “http://maps.googleapis.com/maps/api/geocode/xml?address=&sensor=true”   在第193行的/search_results.php网址中未加载

有没有更好的方法来避免此错误?

我的代码如下:

$geo_address = urlencode($address);

$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$geo_address."&sensor=true";

  $xml =  simplexml_load_file($request_url) or die ("url not loading");
  $status = $xml->status;
  if ($status=="OK") {
    $lat = $xml->result->geometry->location->lat;
    $lon = $xml->result->geometry->location->lng;
  }

1 个答案:

答案 0 :(得分:1)

好像你正在尝试对空地址进行地理编码。您应该在查询Google

之前验证$ geo_address长度
$geo_address = urlencode($address);

if(strlen($geo_address)>0) {

    $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$geo_address."&sensor=true";

    $xml =  simplexml_load_file($request_url) or die ("url not loading");
    $status = $xml->status;
    if ($status=="OK") {
      $lat = $xml->result->geometry->location->lat;
      $lon = $xml->result->geometry->location->lng;
    }
} else {
  die('Invalid address');
}

您应该使用适合您应用的其他错误管理逻辑替换die()。

相关问题