JSON - potatoscript/php GitHub Wiki

JSON in PHP

Overview

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines. It is widely used for API communication, storing configuration data, and exchanging data between front-end and back-end applications.

In this section, we will cover:

  • What is JSON?
  • Encoding PHP Data to JSON
  • Decoding JSON to PHP Data
  • Working with JSON Files in PHP
  • Handling JSON in AJAX Requests
  • Common Issues and Best Practices

1. What is JSON?

JSON is a text-based format that represents structured data using key-value pairs. It is similar to a JavaScript object.

Example JSON Data:

{
    "name": "Lucy Berry",
    "age": 25,
    "email": "[email protected]",
    "languages": ["PHP", "JavaScript", "Python"]
}

JSON vs. PHP Array:

Feature JSON PHP Array
Format Text Array Object
Syntax Uses {} and [] Uses array() or []
Compatibility Works with multiple languages PHP-specific
Storage Can be stored as a string Cannot be directly stored

2. Encoding PHP Data to JSON (json_encode)

The json_encode() function converts PHP data structures (arrays, objects) into a JSON string.

Example 1: Encoding an Associative Array

$data = [
    "name" => "Lucy Berry",
    "age" => 25,
    "email" => "[email protected]"
];

$json = json_encode($data);
echo $json;

Output:

{"name":"Lucy Berry","age":25,"email":"[email protected]"}

Example 2: Encoding a Multi-Dimensional Array

$users = [
    ["name" => "Alice", "email" => "[email protected]"],
    ["name" => "Bob", "email" => "[email protected]"]
];

$json = json_encode($users, JSON_PRETTY_PRINT);
echo $json;

Output (Formatted JSON):

[
    {
        "name": "Alice",
        "email": "[email protected]"
    },
    {
        "name": "Bob",
        "email": "[email protected]"
    }
]

Explanation:

  • JSON_PRETTY_PRINT makes the output more readable.
  • json_encode() returns JSON-formatted data, which can be sent to JavaScript or stored in a database.

3. Decoding JSON to PHP Data (json_decode)

The json_decode() function converts JSON strings into PHP objects or arrays.

Example 1: Decoding JSON to an Object

$json = '{"name":"Lucy Berry","age":25,"email":"[email protected]"}';
$data = json_decode($json);

echo $data->name; // Lucy Berry
echo $data->age;  // 25

Explanation:

  • By default, json_decode() converts JSON into a PHP object.
  • $data->name accesses object properties.

Example 2: Decoding JSON to an Associative Array

$json = '{"name":"Lucy Berry","age":25,"email":"[email protected]"}';
$data = json_decode($json, true);

echo $data["name"]; // Lucy Berry
echo $data["age"];  // 25

Explanation:

  • The second parameter (true) converts JSON into an associative array.
  • $data["name"] accesses array keys instead of object properties.

4. Working with JSON Files in PHP

JSON files are commonly used for storing configuration settings or application data.

Example: Reading a JSON File

Let's say we have a file called data.json:

{
    "name": "Lucy Berry",
    "age": 25,
    "email": "[email protected]"
}

PHP Code to Read the JSON File:

$json = file_get_contents("data.json");
$data = json_decode($json, true);

echo "Name: " . $data["name"];

Example: Writing Data to a JSON File

$data = [
    "name" => "Snoopy",
    "hobby" => "Coding",
    "favorite_food" => "Cookies"
];

$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents("new_data.json", $json);

Explanation:

  • file_get_contents("file.json"): Reads a JSON file.
  • file_put_contents("file.json", $json): Writes JSON data to a file.

5. Handling JSON in AJAX Requests

Example: Sending JSON from JavaScript to PHP

JavaScript Code (Using jQuery AJAX)

let userData = {
    name: "gameboy",
    age: 25
};

$.ajax({
    url: "server.php",
    type: "POST",
    data: JSON.stringify(userData),
    contentType: "application/json",
    success: function(response) {
        console.log(response);
    }
});

PHP Code (server.php)

header("Content-Type: application/json");

$data = json_decode(file_get_contents("php://input"), true);
$response = ["message" => "Received data for " . $data["name"]];

echo json_encode($response);

Explanation:

  • JavaScript sends JSON data using JSON.stringify(userData).
  • PHP reads JSON from php://input and decodes it.
  • PHP sends back a JSON response using json_encode().

6. Common Issues and Best Practices

✅ Validate JSON Before Using

Before using JSON data, validate it to avoid errors.

$json = '{"name":"Lucy"}';
$data = json_decode($json, true);

if (json_last_error() === JSON_ERROR_NONE) {
    echo "Valid JSON";
} else {
    echo "Invalid JSON: " . json_last_error_msg();
}

✅ Use json_encode() Options

  • JSON_PRETTY_PRINT → Pretty formatting.
  • JSON_UNESCAPED_UNICODE → Prevents escaping of Unicode characters.
  • JSON_UNESCAPED_SLASHES → Prevents escaping of slashes.

Example:

$data = ["quote" => "Snoopy says, \"Keep coding!\""];
echo json_encode($data, JSON_UNESCAPED_SLASHES);

Output:

{"quote":"Snoopy says, \"Keep coding!\""}

✅ Ensure Proper Content-Type for JSON Responses

header("Content-Type: application/json");
echo json_encode(["status" => "success"]);

Conclusion

In this section, we covered:

  • What is JSON?
  • Encoding PHP data to JSON (json_encode())
  • Decoding JSON into PHP (json_decode())
  • Reading and Writing JSON files
  • Handling JSON in AJAX requests
  • Common issues and best practices

JSON is an essential format for modern web applications, especially for working with APIs and front-end frameworks like React and Vue.js. Mastering JSON in PHP allows you to create efficient and scalable applications. 🚀