Tutorial to read JSON from PHP

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will show you how to read JSON files from PHP.  JSON format are often use in public API’s.  For example, the OpenWeatherMap.org API provides data in JSON format (and for free if your usage is within these conditions).

This is the link to the JSON data for the current weather in London using metric units…

http://api.openweathermap.org/data/2.5/find?q=London&units=metric

This is what the JSON data looks like …

JSON data

JSON data

There are two records here.  One for the London in Canada (as denoted by “country”:”CA”) and one for the London in Great Britain (as denoted by “country”:”GB”).   It shows that it is 15 degrees Celsius in London in Great Britain.  This is the record we want.  And it shows that the city id for London GB is 2643743.  Now we can access this record directly with this URL…

http://api.openweathermap.org/data/2.5/weather?id=2643743&units=metric

At the time that you are doing it, you can confirm the API data of the temperature by typing in “current temperature in London” into Google.

Reading JSON in PHP

Using the PHP function file_get_contents(), we can read this dataset into a string …

using PHP function file_get_contents

using PHP function file_get_contents

This just gives us a string in $json_data that looks very much like the JSON screen shot shown above with all the curly braces and colon.

json_decode()

We pass that string to another PHP function json_decode() and now the data looks like …

weather data

weather data

This was done via a print_r and then a “view source” in the browser so you can see what is in $decoded_data at this point.

Picking out the data structure

See how the data has become an object with structure.  Now we are able to pick out the temperature by doing something like …

picking out the data structure

picking out the data structure

which results in this …

result from php reading from json

result from php reading from json