Create JSON File from MySQL Database using PHP

January 17, 2021
PHP
Create JSON file using php

Tutorial: Create JSON File from MySQL Database using PHP

Creating a Database on How to Create JSON File from MySQL Database using PHP

How to Create JSON File from MySQL Database using PHP? Please follow this tutorial. First, we are going to create a 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.

You should be able to create a database with tables named database.

Creating a 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');
 
    $data = array();
    $sql = "SELECT * FROM members";
    $query = $conn->query($sql);
    while($row = $query->fetch_assoc()){
        $data[] = $row;
    }
 
    //convert to json
    $data = json_encode($data);
 
    //create json file
    $filename = 'members.json';
    if(file_put_contents($filename, $data)){
        echo 'Json file created';
    } 
    else{
        echo 'An error occured in creating the file';
    }
 
?>
Create JSON File from MySQL Database using PHP

Create JSON File from MySQL Database using PHP

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);

Download Here

 

Leave a Reply

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