Submitting formated JSON with PHP form

 Submitting formatted JSON Data with PHP


e-trainings-html-json-php


In this blog, I am explaining how to store submitted form data in JSON format.
So first I create a form that will allow users to add entries to the site. Entries are stored in a JSON file.  Form having some fields such as


  • postDate
  • title
  • description.

 

When the form is submitted, PHP code checks if $_POST is empty or not.
If not empty  it creates an array called $postArray with submitted form data
Then it passes the array to json_encode() function.
Json_encode built-in function converts PHP array  to JSON object and returns it.
Then I concatenated ',' as a separator with other $json objects.
Next file_put_contents function takes 3 parameters
        1. file_name  // to write json data
        2. json object
        3. flag variable called: FILE_APPEND // appends entry at the end of the json file.

form_2_json.php

<?php

$ans="false";
// check if a form was submitted
if( !empty( $_POST ) ){
	
	// convert form data to json format
	$postArray = array(
	"postDate" => $_POST['postDate'],
	"title" => $_POST['title'],
	"description" => $_POST['description']
	
	); //you might need to process any other post fields you have..
	
	$json = json_encode( $postArray );
	// make sure there were no problems
	//if( json_last_error() != JSON_ERROR_NONE ){
	//exit;  // do your error handling here instead of exiting
	// }
	
	
	$file_name = 'topics.json';
        if( ! filesize( $file_name ) == 0 )
		{
		$json = ','.$json;
		} 
 
      // write to file 
	$ans = file_put_contents( $file_name, $json, FILE_APPEND);

if($ans){
echo "<br />Record Added";

}
 } 
 ?>

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<form name="postform" action="" method="post">
<table class="postarea" id="postarea">
<tbody>
<tr>    <td>Date:</td><td><input type="date" name="postDate"></td></tr>
<tr>    <td>Title:</td><td><input type="text" name="title"></td></tr>
<tr>    <td>Article:</td><td><textarea id="text" rows="5" cols="30" name="description"></textarea> </td> </tr> 
<tr>    <td></td><td> <input type="submit" value="Submit Entry"> </td>    </tr>
</tbody>
</table>
</form>

</body>
</html>
 
 
 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP