← Back to Chapters

PHP Create Dynamic JSON File

? PHP Create Dynamic JSON File

? Quick Overview

In PHP, you can generate JSON files dynamically from arrays or database records. This technique is widely used for APIs, configuration storage, and exporting structured data.

? Key Concepts

  • PHP associative arrays and indexed arrays
  • json_encode() for converting data into JSON
  • file_put_contents() for saving JSON to files
  • Using JSON as a lightweight data exchange format

⚙️ Syntax & Theory

The process involves preparing PHP data, encoding it into JSON format, and writing it to a file. JSON files created this way can be consumed by JavaScript, APIs, mobile apps, or other backend systems.

? Code Example 1: Simple JSON File

? View Code Example
// Create a simple JSON file from an associative array
<?php
$data = array(
"name" => "John Doe",
"email" => "john@example.com",
"age" => 30
);

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

echo "JSON file created successfully!";
?>

? Code Example 2: JSON File from Array of Records

? View Code Example
// Generate JSON from multiple user records
<?php
$users = array(
array("id" => 1, "name" => "Alice", "email" => "alice@example.com"),
array("id" => 2, "name" => "Bob", "email" => "bob@example.com"),
array("id" => 3, "name" => "Charlie", "email" => "charlie@example.com")
);

$jsonData = json_encode($users, JSON_PRETTY_PRINT);
file_put_contents("users.json", $jsonData);

echo "Users JSON file created!";
?>

? Code Example 3: JSON File from Database

? View Code Example
// Fetch database records and export them to JSON
<?php
$conn = new mysqli("localhost", "root", "", "testdb");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

$users = array();
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}

$jsonData = json_encode($users, JSON_PRETTY_PRINT);
file_put_contents("users_from_db.json", $jsonData);

echo "Database JSON file created!";
$conn->close();
?>

? Code Example 4: Append Data to JSON File

? View Code Example
// Read existing JSON, append data, and save again
<?php
$file = "users.json";

$jsonData = file_get_contents($file);
$dataArray = json_decode($jsonData, true);

$dataArray[] = array("id" => 4, "name" => "David", "email" => "david@example.com");

file_put_contents($file, json_encode($dataArray, JSON_PRETTY_PRINT));

echo "New user added!";
?>

? Live Output / Explanation

After running the script, a JSON file is created or updated in the server directory. The file contains structured data that can be reused by other programs or APIs.

? Interactive Concept

You can open the generated JSON file in a browser or editor to visually inspect the structure. Try modifying values and decoding them back into PHP arrays using json_decode().

? Use Cases

  • Creating REST API responses
  • Exporting database records
  • Storing configuration or cache data
  • Sharing structured data between systems

✅ Tips & Best Practices

  • Always use JSON_PRETTY_PRINT for readability
  • Validate data before encoding to JSON
  • Use proper file permissions when writing files
  • Use json_decode(..., true) for associative arrays

? Try It Yourself

  • Create a JSON file for a product catalog using PHP arrays
  • Export user data from a database and decode it back
  • Build a nested JSON structure with categories and items