Retrieve Simple JSON API Data in PHP

  • iftekhar
  • Jul 23, 2017
  • 0 comment
  • 724 Views
  • Print

Today I will share a simple PHP script to show how you can retrieve API data using PHP. For demonstration purpose I will use freegeoip.net public API to grab information of any given IP address. As far as the format is concern, we will use JSON. Sorry, I am not a huge fan of XML. So, here we go.

<?php
// Desired IP address
$ip = '172.217.10.78';

// With Error Reporting: file_get_content();
// Without Error Reporting: @file_get_content();
$content = @file_get_contents('http://freegeoip.net/json/'.$ip);

// Result as an Associative Array: json_decode($var, true);
// Result as an Object: json_decode($var);
$result = json_decode($content, true);

// For Array: $result['key'];
// For Object: $result->city;
echo $result['city'];
?>

On this example, I am simply retrieving a portion(city) of the returned result/data. Actual returned results has much more information which you can find from the FreeGEOIP website.

For the demonstration purpose & for the sake of simplicity I used file_get_content function over cURL which may not be the best choice. One a personal level, I also think using cURL would be the best option then again that’s your own journey and I would leave it up to you to deal with.

Now, please understand that this is a very simple example which does not handle errors. I am also well aware of the fact that this snippet is not ready to be used for production purpose. So, just in case if you decide to use this snippet, please do it at your own risk. Thanks.

References: Error Control Operator, cURL, json_decode.

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.