Hi! In this post we’ll see how to write json to file in php. JSON formatted data is more verbose and human readable. If you want to store data which is easily processable in the future, then json format would be a preferable choice nowadays. In the past I have written several tutorials about handling json data and some of the blog readers asked for a solution to save the json data in a file. I thought writing a separate tutorial on the topic will benefit everyone. Here I have given the php script to write json formatted string to file.
Write JSON to File in PHP
The below php script takes up an multi-dimensional associative array, encode it into json string and then write it into a file.
<?php
// array
$array = Array (
"0" => Array (
"id" => "MMZ301",
"name" => "Michael Bruce",
"designation" => "System Architect"
),
"1" => Array (
"id" => "MMZ385",
"name" => "Jennifer Winters",
"designation" => "Senior Programmer"
),
"2" => Array (
"id" => "MMZ593",
"name" => "Donna Fox",
"designation" => "Office Manager"
)
);
// encode array to json
$json = json_encode(array('data' => $array));
//write json to file
if (file_put_contents("data.json", $json))
echo "JSON file created successfully...";
else
echo "Oops! Error creating json file...";
// data.json
// {"data":[{"id":"MMZ301","name":"Michael Bruce","designation":"System Architect"},{"id":"MMZ385","name":"Jennifer Winters","designation":"Senior Programmer"},{"id":"MMZ593","name":"Donna Fox","designation":"Office Manager"}]}
?>
- The function
json_encode(array('data' => $array))encodes array to json along with a name “data”. - The function
file_put_contents("data.json", $json)writes/stores $json string to the specified file “data.json”.
Also Read:
Likewise you can easily write json to file in php. I hope you find this script useful.