Working With JSON and APIs
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
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
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
| Function | What 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
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.
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
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 solutionWrite 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.
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.
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