How to create JSON File from MySQL Database using PHP

Creating our Database

First, we are going to create the database where we get the data to create our JSON file. I've included a .sql file in the downloadable of this tutorial which is a mysql database file. All you have to do is import the said file. If you have no idea on how to do this, please refer to my tutorial, How import .sql file to restore MySQL database. You should be able to create a database with tables named mydatabase.

Creating our Script

Lastly, we create the script to create our JSON file. We are going to name this file as create_json.php
  1. <?php
  2.         //connection
  3.         $conn = new mysqli('localhost', 'root', '', 'mydatabase');
  4.  
  5.         $data = array();
  6.         $sql = "SELECT * FROM members";
  7.         $query = $conn->query($sql);
  8.         while($row = $query->fetch_assoc()){
  9.                 $data[] = $row;
  10.         }
  11.  
  12.         //convert to json
  13.         $data = json_encode($data);
  14.  
  15.         //create json file
  16.         $filename = 'members.json';
  17.         if(file_put_contents($filename, $data)){
  18.                 echo 'Json file created';
  19.         }
  20.         else{
  21.                 echo 'An error occured in creating the file';
  22.         }
  23.  
  24. ?>
That ends this tutorial. Happy Coding :) ***UPDATE*** If you wanted to pretty print the json file, you can change the line $data = json_encode($data); into $data = json_encode($data, JSON_PRETTY_PRINT);

Comments

Hi my name is Bikash Kandel I love you ❤️ and The last thing I need is the order of the order for the sake

Add new comment