PHP APIs and JSON
# 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:
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().
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().
6. Consuming an External API
To get data from a public API, we can usefile_get_contents() by passing a URL instead of a file path.
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.8. Output Explanations
In the custom API endpoint example, setting theContent-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
trueinjson_decode: If you do$data = json_decode($json);without thetrueparameter, 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.phpfile hasecho "<h1>";or accidental whitespace before the<?phptag, it invalidates the JSON response and breaks the frontend application receiving it.
-
SSL Errors: Using
file_get_contents()onhttps://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 isnull.
-
Use the robust
cURLlibrary instead offile_get_contents()for complex API requests (like sending POST data or Authentication Headers to Stripe).
11. Exercises
- 1. Create a PHP array representing a favorite movie. Encode it to JSON and echo it.
-
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.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 usingjson_encode and json_decode, successfully consumed a live external API, and created your own data endpoint.