Skip to content
Advertisement

Geonames api loop and get city name

$jsonfile = file_get_contents("http://api.geonames.org/searchJSON?username=ksuhiyp&country=pt&maxRows=1000&style=SHORT");
    $jsondata = json_encode($jsonfile);
    $cities = explode(',', $jsondata);
    foreach($cities as $key => $value){
        echo $value;
    }

How can i get only all city names (eg… Lisbon, Porto, Aveiro…) contained in the array?

Here is a sample of the array:

{"totalResultsCount":37305,"geonames":[{"lng":"-9.13333","geonameId":2267057,"countryCode":"PT","name":"Lisbon","toponymName":"Lisbon","lat":"38.71667","fcl":"P","fcode":"PPLC"},{"lng":"-8.61099","geonameId":2735943,"countryCode":"PT","name":"Porto","toponymName":"Porto","lat":"41.14961","fcl":"P","fcode":"PPLA"},{"lng":"-8.42005","geonameId":2742032,"countryCode":"PT","name":"Braga","toponymName":"Braga","lat":"41.55032","fcl":"P","fcode":"PPLA"},{"lng":"-8.8882","geonameId":2262963,"countryCode":"PT","name":"Setúbal","toponymName":"Setúbal","lat":"38.5244","fcl":"P","fcode":"PPLA"},{"lng":"-8.13057","geonameId":2264397,"countryCode":"PT","name":"Portugal","toponymName":"Portuguese Republic","lat":"39.6945","fcl":"A","fcode":"PCLI"},

Advertisement

Answer

For starters, that is a pretty ugly way to get at the data, as you are encoding json data that is already json, and then looping on just pieces of that resulting mangled string.

This will get you a resulting array of just names:

$jsonfile = file_get_contents("http://api.geonames.org/searchJSON?username=ksuhiyp&country=pt&maxRows=1000&style=SHORT");
$geodat = json_decode($jsonfile,true);
$names = array();
foreach($geodat['geonames'] as $geoname) {
    $names[] = $geoname['name'];
}
print_r($names);

Example output:

Array (
    [0] => Lisbon
    [1] => Porto
    [2] => Braga
    [3] => Setúbal
    [4] => Portugal
    [5] => Coimbra
    [6] => Funchal
    [7] => Amadora
    [8] => Queluz
    [9] => Lisbon metropolitan area
    ...
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement