8

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?

1
  • Like any other array or object. Commented Jul 4, 2011 at 11:54

3 Answers 3

20

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much. How would I set a variable for just one element of the array e.g. town name?
$Geonames = $data['geonames'][0]['keyname'];
1

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;

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.