Не удается получить какие-либо результаты json с карты openstreet с использованием Nominatim и php file_get_contents() или Curl

Я пытаюсь получить результаты из файла json, полученного с openstreetmap.org. При вводе URL-адреса в браузер я вижу, что файл json возвращается внутри браузера. Если я попытаюсь прочитать json с помощью php-скрипта, то ничего не произойдет. Нет, если я использую file_get_contents, но также и если я использую curl.

function geocode($address){

    // url encode the address
    $address = urlencode($address);

    //Url openstreetmap
    $url = "https://nominatim.openstreetmap.org/?addressdetails=1&q=$address&format=json&limit=1";

    //  Initiate curl
    $ch = curl_init();
    
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Set the url
    curl_setopt($ch, CURLOPT_URL,$url);

    // Execute
    $result=curl_exec($ch);

    // Closing
    curl_close($ch);

    // Will dump a beauty json :3
    var_dump(json_decode($result, true));

    return json_decode($result, true);

}

А также, если я использую file_get_contents, результатов нет:

function geocode($address){

    // url encode the address
    $address = urlencode($address);

    $url = "http://nominatim.openstreetmap.org/search/?format=json&addressdetails=1&q={$address}&format=json&limit=1";

    // get the json response
    $resp_json = file_get_contents($url);

    return json_decode($resp_json, true);

}

Что я, возможно, делаю неправильно?


person Arjan    schedule 20.02.2021    source источник


Ответы (1)


Я изменил ваш код в соответствии с Политикой использования Nominatim.

Короче говоря, CURL — лучший метод для вас, но вам нужно добавить хотя бы эти заголовки HTTP-запроса:

  • HTTP-референт
  • Пользовательский агент

Также важно не отправлять более 1 запроса в секунду (см. ссылку выше на Политику использования).

Я изменил ваш код, так что это должно работать:

<?php

function geocode($address){
    $address = urlencode($address);

    $url = "https://nominatim.openstreetmap.org/?addressdetails=1&q=$address&format=json&limit=1";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");

    $result = curl_exec($ch);

    curl_close($ch);

    return json_decode($result, true);
}

echo "<pre>";
print_r(geocode("Time Square, New York City"));

Выход:

Array
(
    [0] => Array
        (
            [place_id] => 162597874
            [licence] => Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright
            [osm_type] => way
            [osm_id] => 304980452
            [boundingbox] => Array
                (
                    [0] => 41.7382344
                    [1] => 41.7384706
                    [2] => -74.0371548
                    [3] => -74.0367398
                )

            [lat] => 41.73835325
            [lon] => -74.03694730280651
            [display_name] => Time Square, 652, NY 299, Elting Corners, Lloyd, Town of Lloyd, Ulster County, New York, 12561, United States
            [class] => building
            [type] => yes
            [importance] => 0.401
            [address] => Array
                (
                    [building] => Time Square
                    [house_number] => 652
                    [road] => NY 299
                    [hamlet] => Elting Corners
                    [town] => Lloyd
                    [municipality] => Town of Lloyd
                    [county] => Ulster County
                    [state] => New York
                    [postcode] => 12561
                    [country] => United States
                    [country_code] => us
                )

        )

)
person Martin    schedule 22.02.2021
comment
Ах, теперь я вижу, это работает блестяще! - person Arjan; 22.02.2021