PHP: REST API – file_get_contents()

There are two popular methods to fetch REST API data in PHP. Either you can use PHP built-in function file_get_contents() or use CURL commands.

Working with JSON data in API

XML & JSON are two mostly used API data format. In this chapter, we will use an API that works with JSON data.

Most of the time, it is easy to read or get data from REST API URL. Most applications create dedicated URLs (also called endpoints or routes) to provides access to their data for other applications.

As most APIs use HTTP GET method to read API data, you can simply hit URL in the browser to view data for testing. This is because when you HIT any URL in the browser, it sends GET request and access data. You can search for dummy or sample REST API URLs online for practice.

SAMPLE JSON data format in APIs

We will use Dummy REST API Example website to work with live API data in our examples. This website provides a number of routes or URLs to read, create, update, delete data using API. We will use the following to read employees data.

GET Employees data using API URL:

Above URL provides employee’s profile data in JSON format something similar to the following:


Code to read API data using PHP file_get_contents() function

PHP inbuilt file_get_contents() function is used to read a file into a string. This can read any file or API data using URLs and store data in a variable. This function is the easiest method to read any data by passing API URL.

In the following PHP program, we will use a sample API URL that provides employee’s data and displays them.

$api_url = '';
// Read JSON file
$json_data = file_get_contents($api_url);
// Decode JSON data into PHP array
$response_data = json_decode($json_data);

// All user data exists in 'data' object
$user_data = $response_data->data;
// Cut long data into small & select only first 10 records
$user_data = array_slice($user_data, 0, 9);
// Print data if need to debug
// Traverse array and display user data
foreach ($user_data as $user) {
	echo "name: ".$user->employee_name;
	echo "<br />";
	echo "name: ".$user->employee_age;
	echo "<br /> <br />";

Code Explanation

  1. Pass API URL in file_get_contents() to fetch data
  2. Decode JSON data into PHP array
  3. Select only first 10 records by slicing array. Because given feed data is large, this may slow down your browser to show them all.
  4. Traverse user data array and display the required information.

Using the PHP file_get_contents() function, we can read files or API data but can not perform write, update, delete operations. In the next chapters, we will use cURL methods to perform all those operations using API data.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.