The Goal: Fetching Live Data

In this lesson, we will write a PHP script to connect to a public API, fetch data, and display it on our page. This process is known as "consuming" an API.

We will be using JSONPlaceholder, a free fake REST API that is perfect for testing and prototyping. We'll fetch a list of sample blog posts from their /posts endpoint: https://jsonplaceholder.typicode.com/posts.


Method 1: The Easy Way (file_get_contents)

For simple GET requests where you just need to retrieve data, PHP has a surprisingly easy built-in function.

How it works:

  1. Use file_get_contents() to fetch the raw data from the API endpoint URL. This will return a long string of JSON.
  2. Use json_decode() to convert the JSON string into a PHP array or object.
  3. Loop through the PHP array and display the data!

Example:


<?php

$apiUrl = 'https://jsonplaceholder.typicode.com/posts';

// 1. Fetch the raw JSON data as a string
$json_data = file_get_contents($apiUrl);

// 2. Convert the JSON string into a PHP associative array
// The 'true' argument is important to get an array instead of an object
$posts = json_decode($json_data, true);

// 3. Loop through the array and display the titles
echo "<h1>Latest Posts from API</h1>";
echo "<ul>";
foreach ($posts as $post) {
    echo "<li>" . htmlspecialchars($post['title']) . "</li>";
}
echo "</ul>";

Pros & Cons: This method is incredibly fast and simple for basic GET requests. However, it offers very little control. You cannot easily set custom headers, send POST data, or handle more complex API interactions.


Method 2: The Professional Way (cURL)

cURL (Client URL Library) is the industry-standard tool in PHP for making HTTP requests. It is powerful, flexible, and gives you complete control over every aspect of the request.

The cURL workflow has four main steps:

  1. Initialize (curl_init): Create a new cURL session handle.
  2. Set Options (curl_setopt): Configure the request by setting options like the URL, request type, and headers.
  3. Execute (curl_exec): Perform the request and get the response.
  4. Close (curl_close): Close the cURL session to free up resources.

Example:


<?php

$apiUrl = 'https://jsonplaceholder.typicode.com/posts';

// 1. Initialize cURL
$ch = curl_init();

// 2. Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl);
// This option is crucial: it tells cURL to return the response as a string
// instead of outputting it directly.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// For security, it's good practice to verify the SSL certificate.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

// 3. Execute the cURL session
$json_data = curl_exec($ch);

// 4. Close the cURL session
curl_close($ch);

// After this, the process is the same as before!
$posts = json_decode($json_data, true);

echo "<h1>Latest Posts from API (via cURL)</h1>";
echo "<ul>";
foreach ($posts as $post) {
    echo "<li>" . htmlspecialchars($post['title']) . "</li>";
}
echo "</ul>";


Your Mission

  1. Create a new temporary PHP file in your mvc-project folder (e.g., api-test.php).
  2. Copy and paste the cURL example code into this new file.
  3. Open that file in your browser (e.g., your-site.com/api-test.php).
  4. You should see a list of 100 blog post titles, fetched live from the JSONPlaceholder API!

While file_get_contents is fine for simple tasks, you should practice and prefer using cURL, as it is the tool you will use for all professional API development, including sending POST data and authenticating with headers.