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.
json_encode() for converting data into JSONfile_put_contents() for saving JSON to filesThe 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.
// 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!";
?>
// 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!";
?>
// 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();
?>
// 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!";
?>
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.
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().
JSON_PRETTY_PRINT for readabilityjson_decode(..., true) for associative arrays