Add and Append Data in JSON File using PHP

May 30, 2020
PHP
add and append data to json file

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, please take note that I’ll be using members.json that I have included in the downloadable of this tutorial.

Creating the Script

Lastly, we create the script to load/display the data in our JSON File. 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 load/display 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">Load/Display JSON File using PHP</h1>
    <div class="row">
        <div class="col-sm-8 col-sm-offset-2">
            <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
                        $data = file_get_contents('members.json');
                        $data = json_decode($data);
                        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>

That ends this tutorial. Happy Coding!

Download Here

Leave a Reply

Your email address will not be published. Required fields are marked *