In PHP, you can use the json_encode()
and json_decode()
functions to read and write JSON files. Here's an example of how to do it:
file_get_contents()
function to read the file contents into a string. Then, you can use json_decode()
function to convert that string into a PHP array or object.// Read JSON file
$jsonString = file_get_contents('data.json');
$data = json_decode($jsonString, true); // true parameter converts JSON to associative array
// Access the data
echo $data['name'];
echo $data['age'];
json_encode()
function to convert the PHP array or object into a JSON string, and then use the file_put_contents()
function to write that string to a file.// Create data to be written
$data = array(
'name' => 'John Doe',
'age' => 30
);
// Convert data to JSON string
$jsonString = json_encode($data);
// Write JSON string to file
file_put_contents('data.json', $jsonString);
Remember to replace 'data.json'
with your file path.
Note that when using json_decode()
, the second parameter determines if the resulting data will be converted to an associative array or an object. Using true
makes it an associative array, while omitting it or using false
makes it an object.