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 a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food =["fruits" =>["banana", "apple"), "veggie" =>["collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
Add data from form in text file in JSON format

Last accessed pages

  1. Code Snippets - Add and Create (1800)
  2. Send Email with Nodemailer (3166)
  3. PHP Script Website Mini-Traffic (7080)
  4. SBMD - Simple Backup MySQL Database (5002)
  5. XML Documents (713)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (324)
  2. Read Excel file data in PHP - PhpExcelReader (118)
  3. The Four Agreements (97)
  4. PHP Unzipper - Extract Zip, Rar Archives (94)
  5. The Mastery of Love (87)
Chat
Chat or leave a message for the other users
Full screenInchide