在php中从url获取查询

时间:2012-03-22 17:59:08

标签: php geocoding

我不知道如何在php中执行此操作。我正在尝试从openstreetmap.org获取地理编码数据,但我需要在php中执行此操作。

在Javascript中(我有这个工作),它是:

<script type="text/javascript"
    src="http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671">
</script>

我有那个网址,但我不知道如何在php中执行它。

我试过了:

<?php
    $url = "http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671";
    $response = file_get_contents($url);
?>

但这不起作用。我用curl尝试了同样的方法。任何想法或这种类型的查询在php中都不可能吗?

2 个答案:

答案 0 :(得分:2)

使用此功能;

 $xml = simplexml_load_file("http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671");
 print_r($xml);

将返回一个值数组,见下文;

 SimpleXMLElement Object
 (
     [@attributes] => Array
         (
            [timestamp] => Thu, 22 Mar 12 18:31:11 +0000
            [attribution] => Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.
            [querystring] => format=xml&lat=43.642018&lon=-79.374671
         )

[result] => 1, Yonge Street, Corktown, Toronto, Ontario, M5B2H1, Canada
[addressparts] => SimpleXMLElement Object
    (
        [house_number] => 1
        [road] => Yonge Street
        [suburb] => Corktown
        [city] => Toronto
        [county] => Toronto
        [state] => Ontario
        [postcode] => M5B2H1
        [country] => Canada
        [country_code] => ca
    )

 )

然后操作您认为合适的数据。

答案 1 :(得分:1)

确实返回

<?xml version="1.0" encoding="UTF-8" ?>
<reversegeocode timestamp='Thu, 22 Mar 12 18:07:13 +0000' attribution='Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.' querystring='format=xml&amp;lat=100&amp;Lon=100'>
<error>Unable to geocode</error></reversegeocode>

这只意味着该特定坐标没有地址..但是这有 http://nominatim.openstreetmap.org/reverse?format=xml&lat=52.5487429714954&lon=100

如果您需要更多详细信息,请阅读API