How To Read and Write JSON Files in PHP

Quickly learn how to read from and write to JSON files using PHP.

2 min read β€’
134 1 0

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() and is_readable() before reading files

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Replying to someone. Cancel