simplexml_load_file 警告错误

simplexml_load_file warning error

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

Warning: simplexml_load_file(http://maps.googleapis.com/maps/api/geocode/xml?address=&sensor=true): failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error in /search_results.php on line 193

Warning: simplexml_load_file(): I/O warning : failed to load external entity "http://maps.googleapis.com/maps/api/geocode/xml?address=&sensor=true" in /search_results.php on line 193 url not loading

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

我的代码如下:

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

您似乎在尝试对空地址进行地理编码。您应该在查询 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() 替换为适合您应用的其他一些错误管理逻辑。