简体   繁体   中英

Get a query from url in php

I don't know how to do this in php. I am trying to get geocode data from openstreetmap.org but I need to do this in php.

In Javascript (and I have this working), it's:

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

I have that url but I don't know how to execute it in php.

I have tried:

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

But this doesn't work. I tried the same with curl. Any ideas or is this type of query not possible in php?

Use this;

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

which will return you with an array of the values, see below;

 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
    )

 )

Then manipulate the data however you see fit.

It does return

<?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>

That just means that there is no address for that particular coordinate.. This however has http://nominatim.openstreetmap.org/reverse?format=xml&lat=52.5487429714954&lon=100

Read API if you need more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM