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 = '188.8.131.52'; // 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.