How to Read and Write JSON Files in PHP (With Code Examples)


What You’ll Learn

If you’ve ever needed to store or exchange structured data in a PHP project, JSON files are your best friend. They’re lightweight, human-readable, and easy to handle with just a few built-in PHP functions.

In this guide, you’ll learn how to read a JSON file, decode it into PHP arrays, make changes, and write it back to a file — all with simple, real-world examples.

🔍 What Is JSON and Why Use It?

JSON (JavaScript Object Notation) is a text-based format for representing structured data. It’s often used to transfer information between web applications and servers.

{
  "name": "Bob",
  "email": "[email protected]",
  "skills": ["PHP", "WordPress", "SEO"]
}

PHP has built-in functions that make it easy to work with this kind of data — no external libraries needed.

📂 Step 1: Read a JSON File in PHP

To read a JSON file, we use two functions:

  1. file_get_contents() — reads the file into a string
  2. json_decode() — converts the JSON string into a PHP variable (usually an array)
<?php
$jsonData = file_get_contents('data.json');
$data = json_decode($jsonData, true);

echo $data['name']; // Output: Bob
?>

Breakdown

  • file_get_contents() opens and reads the contents of data.json
  • json_decode() converts the JSON string into an associative array (true tells PHP to return an array instead of an object)

✏️ Step 2: Write Data to a JSON File in PHP

You can also create or update a JSON file using:

  1. json_encode() — turns a PHP array into a JSON string
  2. file_put_contents() — writes that string to a file
<?php
$newData = [
    "name" => "Alice",
    "email" => "[email protected]",
    "skills" => ["HTML", "CSS", "JavaScript"]
];

$jsonString = json_encode($newData, JSON_PRETTY_PRINT);
file_put_contents('data.json', $jsonString);

echo "JSON file created successfully!";
?>

Now your new data.json file will contain:

{
    "name": "Alice",
    "email": "[email protected]",
    "skills": [
        "HTML",
        "CSS",
        "JavaScript"
    ]
}

🔄 Step 3: Update Existing JSON Data

You can combine both steps to read, modify, and save JSON data dynamically:

<?php
$jsonData = file_get_contents('data.json');
$data = json_decode($jsonData, true);

$data['skills'][] = "PHP"; // Add a new skill

file_put_contents('data.json', json_encode($data, JSON_PRETTY_PRINT));

echo "JSON data updated!";
?>

This is a simple way to manage data (like votes, comments, or logs) without needing a full database — ideal for small projects or automation scripts.

⚠️ Common JSON Errors in PHP

If your script fails to decode JSON, check for these:

  • Trailing commas or invalid syntax in your JSON file
  • Missing file path (check permissions)
  • Using json_decode() without true (returns objects instead of arrays)

You can debug with:

json_last_error_msg();

Example:

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

🧩 Step 4: Real-World Example – Simple PHP Logger

Let’s put it all together.
Here’s a lightweight PHP script that logs form submissions or API events into a JSON file.

<?php
function logEvent($eventType, $message) {
    $file = 'log.json';
    $logData = [];

    if (file_exists($file)) {
        $logData = json_decode(file_get_contents($file), true);
    }

    $logData[] = [
        'time' => date('Y-m-d H:i:s'),
        'type' => $eventType,
        'message' => $message
    ];

    file_put_contents($file, json_encode($logData, JSON_PRETTY_PRINT));
}

logEvent('info', 'New user registered.');
echo "Event logged!";
?>

That’s a complete, working JSON-based logger — no database needed.

🧠 Conclusion

Reading and writing JSON files in PHP is simple once you understand how the core functions work.
Use:

  • file_get_contents() to read
  • json_decode() to parse
  • json_encode() + file_put_contents() to write

With these tools, you can manage data efficiently and build lightweight PHP projects that handle structured information like a pro.

Next Up:
How to Parse API Responses in PHP (With JSON Examples) (coming soon)

Categories PHP