Home » Create JSON Files In PHP

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

Requirements:

  • PHP
  • PHP JSON extension – added and enabled by default since PHP 5.2.0

How To Create JSON Files in PHP.

The objective is to generate a JSON file, and name it members.json.

Step 1.

Create a php file, name it generate-json-file.php, and copy/paste the following codes into it.

<?php

// 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
fwrite($handle, $formattedData);

// close the file
fclose($handle);

Step 2.

Execute the file generate-json-file.php in a browser, or in the command line.

$ php create-json-files-in-php.php

Result.

The file members.json will be generated, and it will contain the following data.

{"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"]]}

Notes:

  • Since PHP 5.2.0, JSON extension was added and enabled by default.
  • As of PHP 8.0.0, the JSON extension is a core PHP extension, so it is always enabled.

References:


Posted

in

by

Tags:

2 responses to “Create JSON Files In PHP”

  1. […] File – the result from Create JSON Files In PHP Tutorial will be […]

  2. […] File – the result from Create JSON Files In PHP Tutorial will be […]

Leave a Reply

Your email address will not be published. Required fields are marked *