I'm using an API which returns a JSON string:
http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo
The part I'm interested in is the city/town name (in this instance Hook Norton) which I'd like as a PHP variable. I understand the JSON_decode()
function comes into play somewhere, but how do I access开发者_高级运维 the output of the API?
Try this.
$json = file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo');
$data = json_decode($json,true);
$Geonames = $data['geonames'][0];
echo "<pre>";
print_r($Geonames);
exit;
The simplest way is to use file_get_contents
, which works on web documents as well as local files. For example:
$json = file_get_contents("http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo");
$data = json_decode($json);
echo $data->geonames[0]->toponymName;
Since the JSON is part of the HTTP response, you need to make an HTTP request with PHP and get the response as a string.
The swiss knife for this is cURL, but (depending on your requirements and the server's PHP configuration) you are likely able to do this very simply like this:
$json = file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo');
$data = json_decode($json);
// and now access the data you need
精彩评论