Php-mysql Course

Using in PHP the JSON data saved in text file
Append new form data in JSON string, saved in text file on server

This tutorial shows you how to store data from HTML form in text file on server, in JSON format.

Saving form data in text file, in JSON format

To save data from form:
  1. Get the values of each form item, with $_POST['item_name'] (if method="post"), or with $_GET['item_name'] (if method="get"), and add these data into an array.
  2. Encode the array into a string, in JSON format, using json_encode($array).
  3. Save the JSON string in text file on server, using file_put_contents('path_file.txt', "json_string").

- Here is an example. The following HTML code creates a form with two input text fields, a dropdown select list, two radio buttons, and a submit button. Form data are send to a php file (here "save_json.php").
<form action="save_json.php" method="post">
 Name: <input type="text" name="youname" id="youname" /><br />
 E-mail: <input type="text" name="youemail" id="youemail" /><br />
 Latest studies: <select name="studies" id="studies">
  <option value="">---</option>
  <option value="elementary school">elementary school</option>
  <option value="secondary school">secondary school</option>
  <option value="college">college</option>
  <option value="academic school">academic school</option>
 </select><br />
 Marital status: <input type="radio" name="civilstate" id="civilstate" value="single" />Single
   <input type="radio" name="civilstate" id="civilstate" value="married" />Married<br />
   <input type="submit" id="submit" value="Send" />
</form>
- The PHP code in "save_json.php" that gets data from this form, and saves it into a text file, in JSON format (see the comments in code).
- If the text file already exists, with some data, the code from this example will rewrite the data from that text file with the new form data.
<?php
// Saving data from form in text file in JSON format
// From: https://coursesweb.net/php-mysql/

// check if all form data are submited, else output error message
if(isset($_POST['youname']) && isset($_POST['youemail']) && isset($_POST['studies']) && isset($_POST['civilstate'])) {
  // if form fields are empty, outputs message, else, gets their data
  if(empty($_POST['youname']) || empty($_POST['youemail']) || empty($_POST['studies']) || empty($_POST['civilstate'])) {
    echo 'All fields are required';
  }
  else {
    // adds form data into an array
    $formdata = array(
      'youname'=> $_POST['youname'],
      'youemail'=> $_POST['youemail'],
      'studies'=> $_POST['studies'],
      'civilstate'=> $_POST['civilstate']
    );

    // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
    $jsondata = json_encode($formdata, JSON_PRETTY_PRINT);

    // saves the json string in "formdata.txt" (in "dirdata" folder)
    // outputs error message if data cannot be saved
    if(file_put_contents('dirdata/formdata.txt', $jsondata)) echo 'Data successfully saved';
    else echo 'Unable to save data in "dirdata/formdata.txt"';
  }
}
else echo 'Form fields not submited';
?>
In "formdata.txt" file will be saved a text like this:
{
  "youname": "Some-Name",
  "youemail": "some@email.net",
  "studies": "secondary school",
  "civilstate": "single"
}

Using in PHP the JSON data saved in text file

Once the JSON string is saved in text file on server, to use it in PHP:
  1. Gets the string with data from text file, with file_get_contents('path_file.txt').
  2. Apply json_decode($json_string, true) function to convert data into an array (the true argument is added to convert JSON string into an array. If this argument is not specified, json-string will be converted into an object).

- Example, using form data saved in JSON format, in "dirdata/formdata.txt".
<?php
// Using json-data saved in text file
// From: https://coursesweb.net/php-mysql/

// path and name of the file
$filetxt = 'dirdata/formdata.txt';

// check if the file exists
if(file_exists($filetxt)) {
  // gets json-data from file
  $jsondata = file_get_contents($filetxt);

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

  // Now you can use the array $arr_data with json-data saved in text file
  var_export($arr_data);        // Test to see the array
}
else echo 'The file '. $filetxt .' not exists';
?>
The var_export($arr_data) function from this code will output an array like this:
array ( 'youname' => 'Some-Name', 'youemail' => 'some@email.net', 'studies' => 'secondary school', 'civilstate' => 'single' )

Append new form data in JSON string, saved in text file on server

To append new data submited from form to existing ones, in the JSON string saved in text file:
  1. Get form data, and store them into an array.
  2. Define an empty array that will contain all data.
  3. Get JSON data saved in text file, and store it in that array.
  4. Append the array with form data to the array with JSON from file. Will result a two-dimensional array (each element in main array contains an array with form data).
  5. Convert the array in JSON string and save it in the text file.

- Example code:
<?php
// Append new form data in json string saved in text file
// From: https://coursesweb.net/php-mysql/

// path and name of the file
$filetxt = 'dirdata/formdata.txt';

// check if all form data are submited, else output error message
if(isset($_POST['youname']) && isset($_POST['youemail']) && isset($_POST['studies']) && isset($_POST['civilstate'])) {
  // if form fields are empty, outputs message, else, gets their data
  if(empty($_POST['youname']) || empty($_POST['youemail']) || empty($_POST['studies']) || empty($_POST['civilstate'])) {
    echo 'All fields are required';
  }
  else {
    // gets and adds form data into an array
    $formdata = array(
      'youname'=> $_POST['youname'],
      'youemail'=> $_POST['youemail'],
      'studies'=> $_POST['studies'],
      'civilstate'=> $_POST['civilstate'],
    );

    // path and name of the file
    $filetxt = 'dirdata/formdata.txt';

    $arr_data = array();        // to store all form data

    // check if the file exists
    if(file_exists($filetxt)) {
      // gets json-data from file
      $jsondata = file_get_contents($filetxt);

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

    // appends the array with new form data
    $arr_data[] = $formdata;

    // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

    // saves the json string in "formdata.txt" (in "dirdata" folder)
    // outputs error message if data cannot be saved
    if(file_put_contents('dirdata/formdata.txt', $jsondata)) echo 'Data successfully saved';
    else echo 'Unable to save data in "dirdata/formdata.txt"';
  }
}
else echo 'Form fields not submited';
?>
In "formdata.txt" file will be saved a text like this:
[
  {
    "youname": "Some-Name",
    "youemail": "some@email.net",
    "studies": "secondary school",
    "civilstate": "single"
  },
  {
    "youname": "Other-Name",
    "youemail": "other@email.com",
    "studies": "college",
    "civilstate": "single"
  }
]

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
Add data from form in text file in JSON format

Last accessed pages

  1. JavaScript strip_tags and stripslashes (8825)
  2. Date and Time in ActionScript 3 (10086)
  3. Bind Tool and Control Points (4430)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142539)
  5. Clear Canvas Context (8116)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (542)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)