How to Use PHP to Read and Write from JSON Files
In this lesson, we will see how to use PHP to read and write from JSON files first, we will see how to write an array of data inside the JSON file, and next, we will see how to fetch the written data from the JSON file.
Write data inside the JSON file
First, let's create a new file 'data.json' in which we will write an array of data.
<?php
// Data to be written
$data = [
'name' => 'john',
'age' => '30'
];
// Convert data to JSON string
$jsonString = json_encode($data);
// Write data into the file
file_put_contents('data.json', $jsonString);
Fetch the written data from JSON file
Next, let's fetch the written data from the JSON file.
<?php
// Read data from file
$jsonString = file_get_contents('data.json');
// Convert data into array
$data = json_decode($jsonString, true);
// Display data
echo $data['name'].' '.$data['age'];