Getting Started
I've used Bootstrap in this tutorial which is a CSS framework and is included in the downloadable of this tutorial but if you want, you may download Bootstrap using
this link.
Also, take note that I'll be using
members.json that I have included in the downloadable of this tutorial.
Displaying our JSON Data
Next, we display the existing data in our JSON file and create the add/append form as well. Create a new file, name it as
index.php and paste the codes below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>How to Add/Append Data to JSON File using PHP</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="page-header text-center">Add/Append Data to JSON File</h1>
<div class="row">
<div class="col-sm-3 col-sm-offset-1">
<form method="POST" action="add.php">
<div class="form-group">
<label>ID</label>
<input type="text" class="form-control" name="id">
</div>
<div class="form-group">
<label>Firstname</label>
<input type="text" class="form-control" name="firstname">
</div>
<div class="form-group">
<label>Lastname</label>
<input type="text" class="form-control" name="lastname">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" name="address">
</div>
<div class="form-group">
<label>Gender</label>
<input type="text" class="form-control" name="gender">
</div>
<button type="submit" class="btn btn-primary" name="add">Add</button>
</form>
<?php
if(isset($_SESSION['message'])){
?>
<div class="alert alert-info text-center" style="margin-top:20px;">
<?php echo $_SESSION['message']; ?>
</div>
<?php
unset($_SESSION['message']);
}
?>
</div>
<div class="col-sm-7">
<table class="table table-bordered table-striped">
<thead>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Address</th>
<th>Gender</th>
</thead>
<tbody>
<?php
foreach($data as $row){
echo "
<tr>
<td>".$row->id."</td>
<td>".$row->firstname."</td>
<td>".$row->lastname."</td>
<td>".$row->address."</td>
<td>".$row->gender."</td>
</tr>
";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Creating our Append Script
Lastly, we create the script that adds data to our JSON file. Create a new file, name it as
add.php and paste the codes below.
<?php
if(isset($_POST['add'])){
//data in our POST
'id' => $_POST['id'],
'firstname' => $_POST['firstname'],
'lastname' => $_POST['lastname'],
'address' => $_POST['address'],
'gender' => $_POST['gender']
);
//append the POST data
$data_array[] = $input;
//return to json and put contents to our file
$data_array = json_encode($data_array, JSON_PRETTY_PRINT
);
$_SESSION['message'] = 'Data successfully appended';
}
else{
$_SESSION['message'] = 'Fill up add form first';
}
?>
That ends this tutorial. Happy Coding :)