New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› PHP› Working with JSON and APIs

Working with JSON and APIs

💻 PHP

Encode and decode JSON, call an external API and handle failures gracefully.

Lesson 8 of 9 Tutorial
0 of 9 completed

Modern applications talk to each other in JSON. PHP can read and write it in one line, but the failure cases matter.

By the end of this lesson you can:
  • 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']; // Amina

Calling 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.

Warning Never log or display an API key. Keep secrets in environment variables and read them with getenv().

Practice

  1. Convert an array of students to JSON and back.
  2. Fetch a public API and print one field from the response.
  3. 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

Exercise 1. Safe JSON reader Medium
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.
PHP exercise-1.php
Expected Output
Valid JSON returns the array; invalid JSON returns an empty array.

Lesson Nav

Lesson sections