Get JSON from URL in PHP

On 2/03/2016

In this tutorial, I’m going to show you how to get json from url in php script. JSON has become a popular way to exchange data and web services outputs in json format. To send a HTTP request and parse JSON response from URL is fairly simple in php but newbies may find how to parse json difficult.

Let's see how to build a php json parser script. For this script, I’m going to access Google MAP web service via API and get latitude and longitude co-ordinates for a location. Google map api produces both json/xml output. But for this example I’m going to get the json response and show you how to parse json object to retrieve the geo-metric details.


How to Get JSON from URL in PHP

This is the php script to read the json data from url.

// set location
$address = "Brooklyn+NY+USA";

//set map api url
$url = "$address";

//call api
$json = file_get_contents($url);
$json = json_decode($json);
$lat = $json->results[0]->geometry->location->lat;
$lng = $json->results[0]->geometry->location->lng;
echo "Latitude: " . $lat . ", Longitude: " . $lng;

// output
// Latitude: 40.6781784, Longitude: -73.9441579

The above php script sends a HTTP request to Google MAP web service along with a parameter containing a physical address. The API in turn returns the geometric co-ordinates for the address as json string - which we further decode into a php object and parse it to retrieve the latitude and longitude details.

The php function file_get_contents($url) send a http request to the provided url and returns json data.

The function json_decode($json) decodes the provided json string and returns as a PHP object.

As simple as that you can parse json response. That was all about getting json from url in php.


Contact Form


Email *

Message *