How to create JSON File from MySQL Database using PHP
Submitted by nurhodelta_17 on Monday, March 26, 2018 - 23:53.
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- <?php
- //connection
- $conn = new mysqli('localhost', 'root', '', 'mydatabase');
- $sql = "SELECT * FROM members";
- $query = $conn->query($sql);
- while($row = $query->fetch_assoc()){
- $data[] = $row;
- }
- //convert to json
- //create json file
- $filename = 'members.json';
- echo 'Json file created';
- }
- else{
- echo 'An error occured in creating the file';
- }
- ?>
$data = json_encode($data);
into
$data = json_encode($data, JSON_PRETTY_PRINT);
Comments
Add new comment
- Add new comment
- 1368 views