我有以下代码。我试图从请求的Feed中获取城市名称,并将其添加到新阵列中。任何人都可以给我一个指示。
$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);
编辑 - json响应的1行
{"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},
编辑 - var_dump的响应
array(2) { ["totalResultsCount"]=> int(0) ["geonames"]=> array(0) { } }
答案 0 :(得分:2)
你已经在这个城市的地名部分,所以你不需要有
$city['geonames']['name']
,只是$city['name']
。
答案 1 :(得分:1)
在$city_suggest
上执行var_dump
以查看此变量的结构。有了这些信息,提取所需的数据应该相当容易
但是,试试这个:
$cities[] = $city->name;
答案 2 :(得分:1)
$cities = array();
foreach($city_suggest['geonames'] as $city){
$cities[] = $city['name'];
}
答案 3 :(得分:1)
$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'];
}
另外,请注意您有一行:
$json = @file_get_contents('http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city');
除非您将字符串括在双引号中,否则不会解释 $city
,如下所示:
$json = @file_get_contents("http://ws.geonames.org/searchJSON?country=GB&maxRows=10&name_startsWith=$city");