Read and Write JSON Files in PHP
Quickly learn how to read from and write to JSON files using native PHP functions.
π Why Use JSON in PHP?
JSON (JavaScript Object Notation) is a lightweight format used to store and exchange data. PHP offers built-in functions to read and write JSON, making it easy to create configuration files, mock APIs, or even store structured data for your applications.
βοΈ Writing JSON to a File
Hereβs how to create a JSON file from a PHP array:
<?php
$data = [
"name" => "John Doe",
"email" => "[email protected]",
"age" => 30
];
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents("data.json", $jsonData);
echo "JSON file created successfully.";
?>
This will generate a data.json
file containing the formatted
JSON content.
π Reading JSON from a File
To read and parse a JSON file back into a PHP array:
<?php
$jsonContent = file_get_contents("data.json");
$dataArray = json_decode($jsonContent, true);
print_r($dataArray);
?>
Note the second argument in json_decode()
set to
true
, which converts the data into an associative array.
β Validating JSON Content
Always check that your JSON string was successfully decoded:
<?php
if (json_last_error() === JSON_ERROR_NONE) {
echo "Valid JSON.";
} else {
echo "JSON Error: " . json_last_error_msg();
}
?>
π‘ Common Use Cases
- Store configuration files
- Export/import data for APIs
- Save user preferences locally
- Create lightweight databases for small apps
π οΈ Tips for Working with JSON
- Use
JSON_PRETTY_PRINT
for readable formatting - Always validate JSON after decoding
- Escape special characters before encoding
-
Use
file_exists()
andis_readable()
before reading files