Saturday 25 June 2016

Create dynamic JSON file in PHP Mysql

In this blog We have discuss on how to export mysql data to json file by using php script. Here I will show you how to create dynamic json file from taking data from mysql database and convert that data into one array and convert that array to json file format and then after create dynamic json file. For this things first I have write php code for fetching data from mysql database and storing result into one PHP Associative array. After this I will use json_encode() function, this function will convert php associative array to JSON array. Now JSON array is ready, now I want to create file and put this json array into newly created file, for creating new file, I have use file_put_contents() function, by using this function we can put json array and create new JSON file. So this way we can create dynamic json file from mysql database by using php programming language. If you wanted to learn in details, you can also learn from web development video tutorial which you can find on top of this post and you can also find source code of this in this video also.

Source Code

Database


 --  
 -- Table structure for table `tbl_employee`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_employee` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(50) NOT NULL,  
  `gender` varchar(10) NOT NULL,  
  `designation` varchar(30) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;  
 --  
 -- Dumping data for table `tbl_employee`  
 --  
 INSERT INTO `tbl_employee` (`id`, `name`, `gender`, `designation`) VALUES  
 (1, 'Micheal Bruce', 'Male', 'System Architect'),  
 (5, 'Clara Gilliam', 'Female', 'Programmer');  

create_json_file.php


 <?php  
 //  
 function get_data()  
 {  
      $connect = mysqli_connect("localhost", "root", "", "testing");  
      $query = "SELECT * FROM tbl_employee";  
      $result = mysqli_query($connect, $query);  
      $employee_data = array();  
      while($row = mysqli_fetch_array($result))  
      {  
           $employee_data[] = array(  
                'name'               =>     $row["name"],  
                'gender'          =>     $row["gender"],  
                'designation'     =>     $row["designation"]  
           );  
      }  
      return json_encode($employee_data);  
 }  
 $file_name = date("d-m-Y") . ".json";  
 if(file_put_contents($file_name, get_data()))  
 {  
      echo $file_name . ' File created';  
 }  
 else  
 {  
      echo 'There is some error';  
 }  
 ?>  

1 comment:

  1. Hi , I created .json file but I could not load it into datatable . I checked what was missing and I realized that .json file needs to be wrapped in : {
    "data" : }

    Is it possible to ammend your create_json_file.php so that newly created .json file could be used to insert into datatable

    ReplyDelete