Skip to main content
PHP for Beginners
CHAPTER 27 Beginner

PHP APIs and JSON

Updated: May 12, 2026
25 min read

# Chapter 27: PHP APIs and JSON

1. Introduction

Welcome to Chapter 27! Modern web applications rarely exist in isolation. Your e-commerce site needs to talk to Stripe for payments. Your dashboard needs live weather data from OpenWeather. Your frontend JavaScript (React/Vue) needs data from your PHP backend. How do all these different systems, written in different languages, talk to each other? The answer is APIs (Application Programming Interfaces) and JSON (JavaScript Object Notation). In this chapter, we will learn how to consume external APIs and how to build our own simple API endpoints using PHP.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand what an API is and the universal format of JSON.
  • Convert PHP Arrays into JSON strings using json_encode().
  • Convert JSON strings into PHP Arrays using json_decode().
  • Fetch data from an external API using file_get_contents().
  • Create a basic API endpoint in PHP.

3. What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is completely language-independent. Whether an application is written in PHP, Python, Java, or JavaScript, they can all read and write JSON. It looks very similar to a PHP Associative Array.

JSON Example:

json
12345
{
  "name": "John Doe",
  "age": 28,
  "is_active": true
}

4. Converting PHP to JSON (json_encode)

To send data to a JavaScript frontend or an external API, you must convert your PHP array into a JSON string. We use json_encode().
php
1234567891011121314
<?php
// A PHP Associative Array
$user = [
    "name" => "Alice",
    "email" => "alice@example.com",
    "role" => "admin"
];

// Convert to JSON
$json_data = json_encode($user);

echo $json_data; 
// Outputs: {"name":"Alice","email":"alice@example.com","role":"admin"}
?>

5. Converting JSON to PHP (json_decode)

When you receive JSON from an external API, PHP treats it as a massive, useless string. You must convert it back into a PHP array (or object) to loop through it. We use json_decode().
php
123456789
<?php
$json_string = &#039;{"weather":"Sunny","temperature":75}';

// Convert JSON to PHP Array (The 'true' parameter forces it into an Associative Array)
$php_array = json_decode($json_string, true);

echo "The weather is " . $php_array[&#039;weather']; 
// Outputs: The weather is Sunny
?>

6. Consuming an External API

To get data from a public API, we can use file_get_contents() by passing a URL instead of a file path.
php
12345678910111213
<?php
// Using a free public API for testing
$api_url = "https://jsonplaceholder.typicode.com/users/1";

// 1. Fetch the raw JSON string
$raw_json = file_get_contents($api_url);

// 2. Decode it into a PHP Array
$user_data = json_decode($raw_json, true);

// 3. Use the data!
echo "Fetched User: " . $user_data[&#039;name'];
?>

7. Creating Your Own API Endpoint

If you are building a backend for a mobile app or a React frontend, your PHP file shouldn't output HTML. It should output raw JSON.
php
123456789101112131415
<?php
// api_users.php

// 1. Tell the browser/client that this file outputs JSON, not HTML
header(&#039;Content-Type: application/json');

// 2. Fetch data (Simulated database query)
$users = [
    ["id" => 1, "name" => "John"],
    ["id" => 2, "name" => "Jane"]
];

// 3. Echo the JSON
echo json_encode($users);
?>

8. Output Explanations

In the custom API endpoint example, setting the Content-Type: application/json header is critical. If you don't set it, the browser assumes the output is text/html. By setting it to JSON, frontend frameworks (like Axios or Fetch in JS) will automatically parse the data correctly without throwing errors.

9. Common Mistakes

  • Forgetting true in json_decode: If you do $data = json_decode($json); without the true parameter, PHP converts the JSON into a PHP Object ($data->name), not an Array ($data['name']). Mixing this up causes fatal errors.
  • Echoing HTML in an API: If your api.php file has echo "<h1>"; or accidental whitespace before the <?php tag, it invalidates the JSON response and breaks the frontend application receiving it.
  • SSL Errors: Using file_get_contents() on https:// URLs might fail on local environments (XAMPP) if SSL certificates are not configured properly. (Advanced users use cURL for APIs instead).

10. Best Practices

  • Always check if json_decode() failed by checking if the result is null.
  • Use the robust cURL library instead of file_get_contents() for complex API requests (like sending POST data or Authentication Headers to Stripe).

11. Exercises

  1. 1. Create a PHP array representing a favorite movie. Encode it to JSON and echo it.
  1. 2. Take a JSON string {"status":"success", "message":"Data saved"} and decode it into a PHP array. Echo the message.

12. Mini Project: Random Quote API App

Task: Build a page that fetches a random quote from a public API and displays it neatly using HTML.
php
12345678910111213141516171819202122232425262728293031323334353637
<?php
// 1. Define the API URL (A free random quote API)
$api_url = "https://dummyjson.com/quotes/random";

// 2. Fetch the JSON data
$json_response = file_get_contents($api_url);

// 3. Decode into an associative array
$quote_data = json_decode($json_response, true);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Quote of the Moment</title>
    <style>
        .quote-box {
            font-family: Arial, sans-serif;
            background: #f4f4f4;
            padding: 30px;
            border-left: 5px solid #ff9900;
            max-width: 500px;
            margin: 50px auto;
            text-align: center;
        }
        .quote-text { font-size: 20px; font-style: italic; }
        .author { margin-top: 20px; font-weight: bold; color: #555; }
    </style>
</head>
<body>
    <div class="quote-box">
        <!-- 4. Output the data -->
        <div class="quote-text">"<?php echo htmlspecialchars($quote_data[&#039;quote']); ?>"</div>
        <div class="author">- <?php echo htmlspecialchars($quote_data[&#039;author']); ?></div>
    </div>
</body>
</html>

13. Coding Challenges

Challenge 1: Create an API endpoint (weather_api.php). Create a multidimensional array containing 3 cities and their temperatures. Output the appropriate JSON headers and encode the array so it can be consumed by other applications.

14. MCQs with Answers

1. What does JSON stand for? A) Java Standard Object Network B) JavaScript Object Notation C) JavaScript Oriented Nodes D) Just Some Objects Now *Answer: B*

2. Which function converts a PHP array into a JSON string? A) json_decode() B) array_to_json() C) json_encode() D) string_json() *Answer: C*

3. Why is JSON so widely used? A) Because it is heavily encrypted. B) Because it is faster than databases. C) Because it is language-independent, allowing different systems (PHP, Python, JS) to exchange data seamlessly. D) Because it is the only way to write JavaScript. *Answer: C*

15. Interview Questions

Q: What is an API? *A:* An Application Programming Interface (API) is a set of rules and protocols that allows different software applications to communicate with each other. A Web API typically uses HTTP requests to ask a server for data, which is usually returned in a structured format like JSON.

Q: Explain the difference between json_encode() and json_decode(). *A:* json_encode() serializes PHP variables (like arrays or objects) into a JSON-formatted string, preparing data to be sent out to an API or frontend. json_decode() does the exact opposite; it parses a JSON-formatted string received from an API and converts it back into PHP objects or associative arrays so the script can manipulate the data.

16. FAQs

Q: Do I have to use JSON? What about XML? *A:* XML was the standard data format for APIs 15 years ago (like SOAP APIs). However, JSON is much lighter, easier to read, and works natively with JavaScript. JSON is the undisputed standard for modern RESTful APIs today.

17. Summary

You are now connected to the global ecosystem! You learned what APIs are and how JSON acts as the universal translator between different programming languages. You mastered converting data back and forth using json_encode and json_decode, successfully consumed a live external API, and created your own data endpoint.

18. Next Chapter Recommendation

Throughout this course, we have mixed PHP logic (databases, validations) directly alongside our HTML markup. While fine for small scripts, this becomes unmaintainable for large apps. In Chapter 28: PHP MVC Basics, we will learn the Model-View-Controller architecture, the industry standard for organizing massive codebases!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·