Working with JSON and APIs
💻 PHPEncode and decode JSON, call an external API and handle failures gracefully.
Modern applications talk to each other in JSON. PHP can read and write it in one line, but the failure cases matter.
- Encode and decode JSON safely.
- Call an API with cURL.
- Check status codes and timeouts.
Encode and Decode
Use json_encode and json_decode. Pass true as the second argument to decode into arrays instead of objects.
<?php
$data = [
'name' => 'Amina',
'scores' => [88, 74, 91],
'active' => true,
];
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
$decoded = json_decode($json, true);
echo $decoded['name']; // AminaCalling an API
cURL gives you control over headers, timeouts and errors. Always set a timeout so a slow server cannot freeze your page.
<?php
$ch = curl_init('https://api.example.com/rates');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($response === false) {
echo 'Network error: ' . $error;
} elseif ($status !== 200) {
echo 'Server returned status ' . $status;
} else {
$rates = json_decode($response, true);
print_r($rates);
}Handle Bad JSON
json_decode returns null on invalid input. Check json_last_error() before trusting the result.
Practice
- Convert an array of students to JSON and back.
- Fetch a public API and print one field from the response.
- Add a timeout and a status-code check to the request.
Hands-on exercise
Write a function readJson(string $json): array.
1. Decode the JSON into an array.
2. If decoding fails, return an empty array.
3. Test it with valid JSON and with the string not-json.
Recap
JSON is the common language of APIs. Encode and decode carefully, set timeouts and always check for errors.
Example
<?php
$data = [
'name' => 'Amina',
'scores' => [88, 74, 91],
'active' => true,
];
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
$decoded = json_decode($json, true);
echo $decoded['name']; // Amina
Exercises
1. Decode the JSON into an array.
2. If decoding fails, return an empty array.
3. Test it with valid JSON and with the string not-json.
Expected Output
Valid JSON returns the array; invalid JSON returns an empty array.
Lesson Nav
PHP Course
0/9 lessons completed
- 1 PHP Basics Tutorial
- 2 Functions and Arrays Tutorial
- 3 PHP Forms and User Input Tutorial
- 4 PHP and MySQL Database Tutorial
- 5 Build a Blog System Project
- 6 Classes, Objects and Methods Tutorial
- 7 Validation and Secure Input Tutorial
- 8 Working with JSON and APIs Tutorial
- 9 Project: A Small JSON API Project