Read-Write JSON file using PHP

With reference to my previous post JSON Tutorial in this posts we will see how to read/write data into JSON file.

[
    {
        "firstName": "Vijay",
        "lastName": "reddy",
        "email": "asdv@ymail.com",
        "mobile": ""
    },
    {
        "firstName": "ggdggg",
        "lastName": "nvnvnv",
        "email": "asddd@xmail.com",
        "mobile": ""
    },
    {
        "firstName": "ggdggg",
        "lastName": "nvnvnv",
        "email": "asddd@xmail.com",
        "mobile": ""
    },
    {
        "firstName": "ggdggg",
        "lastName": "nvnvnv",
        "email": "asddd@xmail.com",
        "mobile": ""
    }
]

We will use above user’s data to read and write it into JSON file. Consider we have a form and we will use this form information to write data into JSON file.

<form action="process.php" method="POST">
	First name:<br>
	<input type="text" name="firstName">
	<br><br/>
	Last name:<br>
	<input type="text" name="lastName">
	<br><br>
	  
	Email:<br>
	<input type="text" name="email">
	<br><br>
	  
	Mobile:<br>
	<input type="text" name="mobile">
	<br><br>
	<input type="submit" value="Submit">
</form>

Our form has action attribute which is pointing to process.php file. In process.php we will write below code.

<?php
   	
   $myFile = "data.json";
   $arr_data = array(); // create empty array

  try
  {
	   //Get form data
	   $formdata = array(
	      'firstName'=> $_POST['firstName'],
	      'lastName'=> $_POST['lastName'],
	      'email'=>$_POST['email'],
	      'mobile'=> $_POST['mobile']
	   );

	   //Get data from existing json file
	   $jsondata = file_get_contents($myFile);

	   // converts json data into array
	   $arr_data = json_decode($jsondata, true);

	   // Push user data to array
	   array_push($arr_data,$formdata);

       //Convert updated array to JSON
	   $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
	   
	   //write json data into data.json file
	   if(file_put_contents($myFile, $jsondata)) {
	        echo 'Data successfully saved';
	    }
	   else 
	        echo "error";

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

?>


In above code there is $formdata array in which we are storing form data send by the user. As we have used POST method in our form we are using $POST method in php to get form data. file_get_contents() is PHP function which is used to read data from file. Next we have used json_decode() function to convert JSON data into array. Note this is not a normal text file it’s a JSON file. That’s why we have used json_decode function to convert data into an array. array_push function will add formdata array into existing json array (arr_data). json_encode() will convert array into JSON format, so that we can write this json into json file. Note, we have used JSON_PRETTY_PRINT parameter in json_encode function. This parameter will format our JSON object and store it in json file. If we don’t use this parameter then output which is stored in JSON file will not be well formatted it will be a one line string. JSON_PRETTY_PRINT will work only in PHP version 5.3 and above.

Download source code here

One thought on “Read-Write JSON file using PHP

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>