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 HTML5 tag can be used to embed an external application (SWF, PDF) in web page?
<mark> <embed> <canvas>
<embed src="flash_game.swf" width="450" height="350" />
Which CSS pseudo-element adds a special style to the first line of a text?
:first-letter :before :first-line
#id:first-line {
  font-weight: bold;
  color: blue;
}
Click on the window object property which gets or sets the URL of current page.
window.location window.self window.status
var url = window.location;
alert(url);
Indicate the PHP function used to get the contents of a file or page and store it into a string.
fopen() file_put_contents() file_get_contents()
$homepage = file_get_contents("http://coursesweb.net/");
echo $homepage;
Add data from form in text file in JSON format

Last accessed pages

  1. Disable button and Enable it after specified time (17527)
  2. JavaScript Game - Find the Word (887)
  3. Ajax-PHP Chat Script (49473)
  4. Working with getElementsByTagName (13084)
  5. Node.js Course (2790)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (318)
  2. CSS cursor property - Custom Cursors (56)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (44)
  4. The Mastery of Love (41)
  5. CSS3 2D transforms (40)