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 to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Add data from form in text file in JSON format

Last accessed pages

  1. Get Mime Type of file or string content in PHP (6230)
  2. Countdown Timer with starting time added into a form (11533)
  3. Disable button and Enable it after specified time (17533)
  4. JpGraph - Create Graph, Charts, Plots in PHP (3933)
  5. Simple Admin Login PHP Script (10999)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (477)
  2. CSS cursor property - Custom Cursors (81)
  3. The Mastery of Love (71)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (64)
  5. CSS3 2D transforms (46)