Working With JSON and APIs

Course 2 · Ch 7
Working With JSON and APIs: json_encode/decode, Consuming a REST API With cURL
The data format the web speaks, and how to pull data from someone else's server into your own PHP script

JSON (JavaScript Object Notation) is the standard format for exchanging structured data between systems on the web — virtually every API returns it. This chapter covers converting between PHP arrays and JSON text, then using cURL to actually fetch JSON data from a real external API.

json_encode — PHP Array to JSON Text

<?php $person = [ "name" => "Philip", "age" => 35, "hobbies" => ["reading", "chess"] ]; echo json_encode($person); // {"name":"Philip","age":35,"hobbies":["reading","chess"]} echo json_encode($person, JSON_PRETTY_PRINT); // adds readable indentation ?>

json_encode() turns a PHP array (Chapter 6 of Fundamentals) into a JSON-formatted string — used constantly when a PHP script needs to send data out, whether as an API response or for storing structured data as text.

json_decode — JSON Text Back to PHP

<?php $json = '{"name":"Philip","age":35}'; $object = json_decode($json); // returns a stdClass OBJECT by default echo $object->name; // "Philip" — accessed with -> like any object $array = json_decode($json, true); // "true" here means "return an associative array instead" echo $array['name']; // "Philip" — accessed with ['key'] instead ?>
json_decode's second argument — easy to forget, and changes the result type completely
Without the true second argument, json_decode() returns a generic stdClass object, accessed with -> property syntax. Passing true returns a familiar associative array instead, accessed with ['key'] syntax. Most PHP code dealing with API responses uses true consistently, simply because arrays are usually more convenient to work with using the tools from Chapter 6 of Fundamentals (foreach, array functions, etc).

cURL — Making an HTTP Request From PHP

<?php $ch = curl_init("https://api.example.com/users/1"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the response as a string, don't print it directly $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 200) { $user = json_decode($response, true); echo "Got user: " . $user['name']; } else { echo "Request failed with status $httpCode"; } ?>
curl_init() curl_exec() → API JSON string response
curl_init() configures the request, curl_exec() actually sends it and waits for the response
FunctionWhat it does
curl_init($url)Starts a new cURL request, targeting a URL
curl_setopt($ch, OPTION, value)Configures the request (return as string, POST data, headers, etc.)
curl_exec($ch)Actually sends the request, returns the response body
curl_getinfo($ch, CURLINFO_HTTP_CODE)Gets the HTTP status code (200, 404, 500, etc.)
curl_close($ch)Frees the cURL resource — good practice once done

Sending Data — A POST Request

<?php $data = ["title" => "New Post", "body" => "Hello!"]; $ch = curl_init("https://api.example.com/posts"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); $response = curl_exec($ch); curl_close($ch); ?>

Sending data to an API mirrors submitting a form (Chapter 8 of Fundamentals), but the data is JSON-encoded first, and the Content-Type: application/json header tells the receiving API exactly what format the body is in.

Always check the HTTP status code before trusting a response
A request can "succeed" from cURL's perspective (no connection error) while the API itself reports a failure via its status code — checking for 200 (success) or other expected codes, rather than assuming the response is always valid, is good practice exactly like checking $_SERVER['REQUEST_METHOD'] before trusting $_POST in Chapter 8 of Fundamentals.

Coding Challenges

Challenge 1

Create an associative array representing a product (name, price, in_stock as a boolean). Encode it to JSON with json_encode(), echo it, then decode that exact JSON string back into a PHP array with json_decode(), and echo the price from the decoded array to confirm round-tripping worked correctly.

📄 View solution
Challenge 2

Write a function fetchJson($url) that uses cURL to GET a URL, checks the HTTP status code, and returns the decoded JSON as an associative array if the code is 200, or null otherwise. Call it with a placeholder URL and handle both possible outcomes.

📄 View solution
Challenge 3

Write a function postJson($url, $data) that sends an associative array as a JSON-encoded POST request with the correct Content-Type header, and returns the decoded JSON response. Show how it would be called with a sample $data array.

📄 View solution

Chapter 7 Quick Reference

  • json_encode($array) — PHP array → JSON string; add JSON_PRETTY_PRINT for readable formatting
  • json_decode($json, true) — JSON string → PHP array (true = associative array, not stdClass)
  • curl_init($url) → curl_setopt() → curl_exec() → curl_close() — the standard cURL request pattern
  • CURLOPT_RETURNTRANSFER — returns the response as a string instead of printing it directly
  • curl_getinfo($ch, CURLINFO_HTTP_CODE) — always check this before trusting a response
  • CURLOPT_POST / CURLOPT_POSTFIELDS — sending data; pair with json_encode() and the Content-Type header for JSON APIs
  • Next chapter: file uploads and handling user input safely