Url 地理编码请求未加载错误

Url not loading error on geocoding requests

我以前有一个 Google 地理编码脚本,用于使用数据库中的本地地址提取经度和纬度。

在过去的 6 个月里,我更换了主机,显然 Google 已经实施了一个新的正向地理编码器。现在只是 return 是 url 未从 xml 脚本调用加载错误。

我已尽一切努力让我的代码正常工作。即使是来自其他网站的示例代码也无法在我的服务器上运行。我错过了什么?是否可能有服务器端设置阻止它正常执行?

尝试 # 1:

$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?new_forward_geocoder=true&address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
echo $request_url;
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
return $status;

只是 returns url 未加载。我试过使用和不使用 new_forwad_geocoder。我也尝试过使用和不使用 https。

如果您只需将 $request_url 字符串复制并粘贴到浏览器,它 return 会产生正确的结果。

也试过这个只是为了看看我是否可以得到一个文件到 return。尝试 2:

$request_url = "http://maps.googleapis.com/maps/api/geocode/json?new_forward_geocoder=true&address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";//&sensor=true
echo $request_url."<br>";
$tmp = file_get_contents($request_url);
echo $tmp;

知道可能导致连接失败的原因吗?

我再也无法使用 XML 进行此操作,file_get_contents 调用是我几乎可以肯定的罪魁祸首。

我已经发布了我在 JSON/Curl 中所做的工作(见下文),以防有人遇到类似问题。

最终,我认为我 运行 遇到的问题与升级到服务器上的 Apache 版本有关;一些与 file_get_contents 和 fopen 相关的默认设置更具限制性。不过我还没有证实这一点。

这段代码确实有效:

class geocoder{
    static private $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=";

    static public function getLocation($address){
        $url = self::$url.$address;

        $resp_json = self::curl_file_get_contents($url);
        $resp = json_decode($resp_json, true);
        //var_dump($resp);
        if($resp['status']='OK'){
          //var_dump($resp['results'][0]['geometry']['location']);
            //echo "<br>";
            //var_dump($resp['results'][0]['geometry']['location_type']);
            //echo "<br>";
            //var_dump($resp['results'][0]['place_id']);

            return array ($resp['results'][0]['geometry']['location'], $resp['results'][0]['geometry']['location_type'], $resp['results'][0]['place_id']);
        }else{
            return false;
        }
    }

    static private function curl_file_get_contents($URL){
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        curl_close($c);

        if ($contents) return $contents;
            else return FALSE;
    }
}

$Address = "1600 Amphitheatre Parkway, Mountain View, CA";
$Address = urlencode(trim($Address));

list ($loc, $type, $place_id) = geocoder::getLocation($Address);
//var_dump($loc);
$lat = $loc["lat"];
$lng = $loc["lng"];
echo "<br><br> Address: ".$Address;
echo "<br>Lat: ".$lat;
echo "<br>Lon: ".$lng;
echo "<br>Location: ".$type;
echo "<br>Place ID: ".$place_id;