Create a JSON file in PHP

February 23, 2014 | Last tested: May 2015 | 1297 views | Comments

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

Format the values using the function json_encode(), and generate the JSON file with the use of the following functions, fopen(), fwrite(), and fclose() in PHP.

For example.

Generate a JSON file, name it members.json.

//prepare the data
$data = array();
$data['members'] = array(
	0 => array('Jackson','Barbara','27','F','Florida'),
	1 => array('Kimball','Andrew','25','M','Texas'),
	2 => array('Baker','John','28','M','Arkansas'),
	3 => array('Gamble','Edward','29','M','Virginia'),
	4 => array('Anderson','Kimberly','23','F','Tennessee'),
	5 => array('Houston','Franchine','25','F','Idaho'),
	6 => array('Franklin','Howard','24','M','California'),
	7 => array('Chen','Dan','26','M','Washington'),
	8 => array('Daniel','Carolyn','27','F','North Carolina'),
	9 => array('Englert','Grant','25','M','Delaware')

//format the data
$formattedData = json_encode($data);

//set the filename
$filename = 'members.json';

//open or create the file
$handle = fopen($filename,'w+');

//write the data into the file

//close the file


The file members.json will have these values;

{"members":[["Jackson","Barbara","27","F","Florida"],["Kimball","Andrew","25","M","Texas"],["Baker","John","28","M","Arkansas"],["Gamble","Edward","29","M","Virginia"],["Anderson","Kimberly","23","F","Tennessee"],["Houston","Franchine","25","F","Idaho"],["Franklin","Howard","24","M","California"],["Chen","Dan","26","M","Washington"],["Daniel","Carolyn","27","F","North Carolina"],["Englert","Grant","25","M","Delaware"]]}

Please mouse over here to view the image.

Note: A read/write permission must be granted to the folder where the json file will be saved.