Reputation: 5271
I have the following code. I am trying to get just the name of the city out of the feed that is requested, and into a new array. Can anyone give me an indication.
$city = $_GET['city'];
$json = @file_get_contents('http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city');
$json = utf8_encode($json);
$city_suggest = json_decode($json, true);
foreach($city_suggest['geonames'] as $city){
$cities = $city['geonames']['name'];
}
print_r ($cities);
Edit - 1 line of the json response
{"totalResultsCount":323,"geonames":[{"countryName":"United Kingdom","adminCode1":"ENG","fclName":"city, village,...","countryCode":"GB","lng":-0.12883186340332,"fcodeName":"capital of a political entity","toponymName":"London","fcl":"P","name":"London","fcode":"PPLC","geonameId":2643743,"lat":51.5005149421307,"adminName1":"England","population":7556900},
Edit - response of var_dump
array(2) { ["totalResultsCount"]=> int(0) ["geonames"]=> array(0) { } }
Upvotes: 1
Views: 1729
Reputation: 34013
$city = $_GET['city'];
$json = file_get_contents("http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=" . rawurlencode($city));
$json = utf8_encode($json);
$city_suggest = json_decode($json, true);
foreach($city_suggest['geonames'] as $city){
print $city['name'];
// there are other available variables too
// print $city['countryName'];
// print $city['adminCode1'];
// print $city['fclName'];
// print $city['countryCode'];
// print $city['lng'];
// print $city['fcodeName'];
// print $city['toponymName'];
// print $city['fcl'];
// print $city['name'];
// print $city['fcode'];
// print $city['geonameId'];
// print $city['lat'];
// print $city['adminName1'];
// print $city['population'];
}
Also, note that you have a line:
$json = @file_get_contents('http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city');
$city
will not be interpreted unless you enclose the string in double quotes, like this:
$json = @file_get_contents("http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city");
Upvotes: 1
Reputation: 30394
$cities = array();
foreach($city_suggest['geonames'] as $city){
$cities[] = $city['name'];
}
Upvotes: 1
Reputation: 1743
You're already in the geonames part of the city in your foreach, so you don't need to have
$city['geonames']['name']
, just $city['name']
.
Upvotes: 2
Reputation: 53603
Do var_dump
on $city_suggest
to see the structure of this variable. With that info, it should be fairly easy to extract the data you need.
But, try this instead:
$cities[] = $city->name;
Upvotes: 1