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.

php-get-json-from-url

How to Get JSON from URL in PHP

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

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

//set map api url
$url = "http://maps.google.com/maps/api/geocode/json?address=$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.

4 comments:

  1. Yes, JSON from URL in PHP code is right.

    ReplyDelete
  2. how to view data if using multiple json data..??

    ReplyDelete
  3. Your blog inspires me every time when I read it. I love reading blogs. I don't excite always by reading blog posts. But in your blog I find something that implies in blogging. Anyway, you’re unquestionably a great blogger and you have a skill to make your reader to keep reading your blog again and again. Keep up the magnificent work. Continue moving the people! This is one of the veru interesting post. Because I am new in blogging and I require great instructional exercise like your post.
    best resume writing service

    ReplyDelete

Contact Form

Name

Email *

Message *