使用 PHP (curl) 从 JSON 中提取数据(Google Maps API)
我对JSON相当陌生,我正在尝试使用curl从Google Maps API获取地理编码城市的纬度和经度。我正在使用的函数是:
function geocode($city){
$cityclean = str_replace (" ", "+", $city);
$details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geoloc = json_decode(curl_exec($ch), true);
$step1 = $geoloc['results'];
$step2 = $step1['geometry'];
$coords = $step2['location'];
print $coords['lat'];
print $coords['lng'];
}
所有这一切的目标是从以下 JSON 的 Results -> Geometry -> Location 数组中提取 lat 和 lng 值:
{
"status": "OK",
"results": [ {
"types": [ "locality", "political" ],
"formatted_address": "Westminster, London, UK",
"address_components": [ {
"long_name": "London",
"short_name": "London",
"types": [ "locality", "political" ]
}, {
"long_name": "Westminster",
"short_name": "Westminster",
"types": [ "administrative_area_level_3", "political" ]
}, {
"long_name": "Greater London",
"short_name": "Greater London",
"types": [ "administrative_area_level_2", "political" ]
}, {
"long_name": "England",
"short_name": "England",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United Kingdom",
"short_name": "GB",
"types": [ "country", "political" ]
} ],
"geometry": {
"location": {
"lat": 51.5001524,
"lng": -0.1262362
},
"location_type": "APPROXIMATE",
"viewport": {
"southwest": {
"lat": 51.3493528,
"lng": -0.3783580
},
"northeast": {
"lat": 51.7040647,
"lng": 0.1502295
}
},
"bounds": {
"southwest": {
"lat": 51.3493528,
"lng": -0.3783580
},
"northeast": {
"lat": 51.7040647,
"lng": 0.1502295
}
}
}
} ]
}
但是,它不会打印任何内容。我知道该函数成功地从Google检索了JSON并将其带到我的服务器,因为我为“status”值执行了打印语句,并返回了“OK”。问题似乎在于当我尝试深入研究JSON时。
抱歉,如果这是一个简单的问题,但就像我说的,我是新手,它现在让我发疯。
多谢!:)