PHP JSON

Working with JSON data in PHP applications

📦 What is JSON?

JSON (JavaScript Object Notation) is a lightweight data format for storing and exchanging data. PHP provides built-in functions to encode PHP data into JSON and decode JSON back into PHP arrays or objects.


<?php
// PHP array to JSON
$data = ["name" => "John", "age" => 30];
$json = json_encode($data);
echo $json; // Output: {"name":"John","age":30}
?>
                                    

Output:

{"name":"John","age":30}

JSON Operations

📤

json_encode()

Convert PHP arrays and objects into JSON strings for storage or API responses.

<?php
$user = [
    "name" => "Alice",
    "email" => "[email protected]"
];
$json = json_encode($user);
?>
📥

json_decode()

Parse JSON strings back into PHP arrays or objects for processing in your application.

<?php
$json = '{"name":"Bob","age":25}';
$data = json_decode($json, true);
echo $data["name"]; // Bob
?>
⚙️

JSON Options

Use flags to control JSON formatting like pretty printing, escaping, and Unicode handling.

<?php
$json = json_encode(
    $data,
    JSON_PRETTY_PRINT
);
?>
🔍

Error Handling

Check for JSON errors using json_last_error() to handle invalid or malformed JSON data.

<?php
json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error!";
}
?>

🔹 Encoding PHP to JSON

Convert PHP arrays into JSON strings using json_encode():

<?php
// Simple array
$colors = ["red", "green", "blue"];
$json1 = json_encode($colors);
echo "Array: $json1<br><br>";

// Associative array
$person = [
    "name" => "John Doe",
    "age" => 30,
    "city" => "New York"
];
$json2 = json_encode($person);
echo "Object: $json2<br><br>";

// Nested array
$data = [
    "user" => "Alice",
    "scores" => [85, 90, 78]
];
$json3 = json_encode($data);
echo "Nested: $json3";
?>

Output:

Array: ["red","green","blue"]

Object: {"name":"John Doe","age":30,"city":"New York"}

Nested: {"user":"Alice","scores":[85,90,78]}

🔹 Decoding JSON to PHP

Parse JSON strings back into PHP data structures:

<?php
$json = '{"name":"Bob","age":25,"city":"London"}';

// Decode as associative array
$array = json_decode($json, true);
echo "As Array:<br>";
echo "Name: {$array['name']}<br>";
echo "Age: {$array['age']}<br><br>";

// Decode as object
$object = json_decode($json);
echo "As Object:<br>";
echo "Name: {$object->name}<br>";
echo "City: {$object->city}";
?>

Output:

As Array:
Name: Bob
Age: 25

As Object:
Name: Bob
City: London

🔹 Pretty Printing JSON

Format JSON with indentation for better readability:

<?php
$data = [
    "name" => "Alice",
    "email" => "[email protected]",
    "address" => [
        "street" => "123 Main St",
        "city" => "Boston"
    ]
];

// Without pretty print
$compact = json_encode($data);
echo "Compact:<br>$compact<br><br>";

// With pretty print
$pretty = json_encode($data, JSON_PRETTY_PRINT);
echo "Pretty:<br><pre>$pretty</pre>";
?>

Output:

Compact:
{"name":"Alice","email":"[email protected]","address":{"street":"123 Main St","city":"Boston"}}

Pretty:

{
    "name": "Alice",
    "email": "[email protected]",
    "address": {
        "street": "123 Main St",
        "city": "Boston"
    }
}

🔹 Working with JSON Files

Read from and write to JSON files:

<?php
// Data to save
$users = [
    ["id" => 1, "name" => "John"],
    ["id" => 2, "name" => "Jane"]
];

// Write to file
$json = json_encode($users, JSON_PRETTY_PRINT);
file_put_contents("users.json", $json);
echo "Data saved to users.json<br><br>";

// Read from file
$fileContent = file_get_contents("users.json");
$loadedUsers = json_decode($fileContent, true);

echo "Loaded users:<br>";
foreach ($loadedUsers as $user) {
    echo "ID: {$user['id']}, Name: {$user['name']}<br>";
}
?>

Output:

Data saved to users.json

Loaded users:
ID: 1, Name: John
ID: 2, Name: Jane

🔹 JSON Error Handling

Check for errors when encoding or decoding JSON:

<?php
// Invalid JSON
$invalidJson = '{"name":"Bob","age":}';

$result = json_decode($invalidJson);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg() . "<br><br>";
}

// Valid JSON
$validJson = '{"name":"Bob","age":25}';
$result = json_decode($validJson);

if (json_last_error() === JSON_ERROR_NONE) {
    echo "Valid JSON decoded successfully!<br>";
    echo "Name: {$result->name}";
}
?>

Output:

JSON Error: Syntax error

Valid JSON decoded successfully!
Name: Bob

🔹 JSON Encoding Options

Use flags to control JSON output format:

<?php
$data = [
    "name" => "Alice",
    "url" => "https://example.com/profile",
    "tags" => ["php", "json", "api"]
];

// Default encoding
echo "Default:<br>";
echo json_encode($data) . "<br><br>";

// Don't escape slashes
echo "Unescaped slashes:<br>";
echo json_encode($data, JSON_UNESCAPED_SLASHES) . "<br><br>";

// Force object instead of array
echo "Force object:<br>";
echo json_encode($data["tags"], JSON_FORCE_OBJECT);
?>

Output:

Default:
{"name":"Alice","url":"https:\/\/example.com\/profile","tags":["php","json","api"]}

Unescaped slashes:
{"name":"Alice","url":"https://example.com/profile","tags":["php","json","api"]}

Force object:
{"0":"php","1":"json","2":"api"}

🔹 Creating JSON APIs

Return JSON responses for API endpoints:

<?php
// Set JSON header
header('Content-Type: application/json');

// Sample API response
$response = [
    "status" => "success",
    "data" => [
        "users" => [
            ["id" => 1, "name" => "John"],
            ["id" => 2, "name" => "Jane"]
        ]
    ],
    "message" => "Users retrieved successfully"
];

// Output JSON
echo json_encode($response, JSON_PRETTY_PRINT);
?>

Output:

{
    "status": "success",
    "data": {
        "users": [
            {"id": 1, "name": "John"},
            {"id": 2, "name": "Jane"}
        ]
    },
    "message": "Users retrieved successfully"
}

🔹 Common JSON Options

Encoding Options:

  • JSON_PRETTY_PRINT - Format with whitespace for readability
  • JSON_UNESCAPED_SLASHES - Don't escape forward slashes
  • JSON_UNESCAPED_UNICODE - Don't escape Unicode characters
  • JSON_FORCE_OBJECT - Output objects instead of arrays
  • JSON_NUMERIC_CHECK - Convert numeric strings to numbers

Common Errors:

  • JSON_ERROR_NONE - No error occurred
  • JSON_ERROR_SYNTAX - Syntax error, malformed JSON
  • JSON_ERROR_DEPTH - Maximum stack depth exceeded
  • JSON_ERROR_UTF8 - Malformed UTF-8 characters

🧠 Test Your Knowledge

Which function converts PHP arrays to JSON?