tags:

views:

53

answers:

4

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) { } } 
+1  A: 

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; 
Itay Moav
ONLY if the call to `json_decode` was `json_decode($json, false);`
artlung
+2  A: 

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'].

Jody
That was the real reason. It turned out that one of the other reasons why it took me 10 minutes to sort out was I accidentally put a rogue symbol into the JSON URL. It was all working but returning nothing. Many thanks.
kalpaitch
+1  A: 
$cities = array();
foreach($city_suggest['geonames'] as $city){
    $cities[] = $city['name'];    
}
Scott Saunders
good point. Thanks
kalpaitch
+1  A: 
$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");
artlung