2010-07-08 71 views
1

我有以下代码。我试图从请求的提要中获取城市的名称,并将其转换为新的数组。任何人都可以给我一个指示。从json响应中获取城市数组

$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); 

编辑 - 1线JSON响应

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

你应该告诉我们$ city_suggest – 2010-07-08 17:50:54

+0

是做什么的(我相信你有问题;-))'var_dump(json_decod e($ json,true))' 可能是因为file_get_contents使用单引号而不是双引号。 – 2010-07-08 18:01:20

+0

你的json调用是错误的,你传递$ city作为URL的一部分,而不是将它连接到最后。 – 2010-07-08 18:03:04

回答

2

你在你的foreach城市GEONAMES一部分是已经,所以你不需要有
$city['geonames']['name'],只是$city['name']

+0

这才是真正的原因。事实证明,我花了10分钟解决问题的其他原因之一是我不小心将一个流氓符号放入JSON URL中。它一切正常,但什么也没有返回。非常感谢。 – kalpaitch 2010-07-08 18:05:24

1

的响应请var_dump$city_suggest看到这个可变的结构。有了这些信息,提取您需要的数据应该相当容易。
不过,试试这个来代替:

$cities[] = $city->name; 
+0

只有当调用json_decode'是'json_decode($ json,false);' – artlung 2010-07-08 18:49:50

1
$cities = array(); 
foreach($city_suggest['geonames'] as $city){ 
    $cities[] = $city['name'];  
} 
+0

好点。谢谢 – kalpaitch 2010-07-08 18:03:53

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");