How to Write JSON File in PHP: Simple Guide
To write a JSON file in PHP, use
json_encode() to convert your data to JSON format, then save it with file_put_contents(). This creates or overwrites the file with the JSON string.Syntax
Use json_encode() to convert PHP arrays or objects into a JSON string. Then use file_put_contents() to write that string to a file.
json_encode($data): Converts PHP data to JSON format.file_put_contents($filename, $jsonString): Writes the JSON string to the file.
php
<?php
$jsonString = json_encode($data);
file_put_contents('filename.json', $jsonString);
?>Example
This example shows how to create an array, convert it to JSON, and save it to a file named data.json.
php
<?php // Sample data array $data = [ 'name' => 'Alice', 'age' => 30, 'city' => 'Wonderland' ]; // Convert array to JSON string $jsonString = json_encode($data, JSON_PRETTY_PRINT); // Write JSON string to file file_put_contents('data.json', $jsonString); // Output success message echo "JSON file created successfully."; ?>
Output
JSON file created successfully.
Common Pitfalls
Common mistakes when writing JSON files in PHP include:
- Not checking if
json_encode()returnsfalsedue to invalid data. - Forgetting to handle file write errors from
file_put_contents(). - Not using
JSON_PRETTY_PRINTfor readable JSON output. - Writing to a file without proper permissions.
Always check for errors and ensure your PHP script has permission to write files.
php
<?php // Wrong way: ignoring errors $jsonString = json_encode($data); file_put_contents('data.json', $jsonString); // Right way: check for errors $jsonString = json_encode($data); if ($jsonString === false) { echo "JSON encoding error: " . json_last_error_msg(); exit; } if (file_put_contents('data.json', $jsonString) === false) { echo "Failed to write to file."; exit; } ?>
Quick Reference
Here is a quick summary of the main functions used:
| Function | Purpose |
|---|---|
| json_encode($data, JSON_PRETTY_PRINT) | Convert PHP data to JSON string with readable format |
| file_put_contents($filename, $jsonString) | Write JSON string to a file |
| json_last_error_msg() | Get last JSON error message if encoding fails |
Key Takeaways
Use json_encode() to convert PHP data to JSON format before writing.
Write JSON string to a file with file_put_contents().
Check for errors from json_encode() and file_put_contents() to avoid silent failures.
Use JSON_PRETTY_PRINT for readable JSON files.
Ensure your PHP script has permission to write to the target file.