Retrieve Simple JSON API Data in PHP

Today I will share a simple PHP script to show how you can retrieve API data using PHP. For demonstration purpose I will use 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.
// Desired IP address
$ip = '';

// With Error Reporting: file_get_content();
// Without Error Reporting: @file_get_content();
$content = @file_get_contents(''.$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.


Commenting is disabled.