CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New
Need a Website Or Web Application Contact : +91 9437911966 (Whatsapp) Note: Paid Service

How to Export MySQL Table to JSON File in CodeIgniter


SQL Query

CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `fname` varchar(30) NOT NULL,
  `lname` varchar(30) NOT NULL,
  `email` varchar(60) NOT NULL,
  `city` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;

INSERT INTO `users` (`id`, `fname`, `lname`, `email`, `city`) VALUES
(1, 'anti', 'warner', 'warneranti34@yahoo.com', 'Las Vegas'),
(2, 'john', 'Taylor', 'taylorjohn@yahoo.com', 'San Francisco'),
(3, 'santener', 'Greyson', 'santener@gmail.com', 'New York'),
(4, 'Henry', 'lee', 'henrylee@gmail.com', 'Los Angeles'),
(5, 'jack', 'kelly', 'jack12@gmail.com', 'New York');

UserModel.php

<?php
class UserModel extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function toJSON()
    {
          $query = $this->db->get('users');
          return json_encode($query->result(), JSON_PRETTY_PRINT);
    }
}
?>

UserController.php

<?php
class UserController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('file');
        $this->load->database();
    }
    
    public function index()
    {
        $this->load->model('UserModel');
        $result = $this->UserModel->toJSON();
        if(write_file('user_data.json', $result))
             echo 'Successfully exported to json file!';
        else
             echo 'Error exporting mysql data...';
    }
}
?>

user_data.json

[
    {
        "id": "1",
        "fname": "anti",
        "lname": "warner",
        "email": "warneranti34@yahoo.com",
        "city": "Las Vegas"
    },
    {
        "id": "2",
        "fname": "john",
        "lname": "Taylor",
        "email": "taylorjohn@yahoo.com",
        "city": "San Francisco"
    },
    {
        "id": "3",
        "fname": "santener",
        "lname": "Greyson",
        "email": "santener@gmail.com",
        "city": "New York"
    },
    {
        "id": "4",
        "fname": "Henry",
        "lname": "lee",
        "email": "henrylee@gmail.com",
        "city": "Los Angeles"
    },
    {
        "id": "5",
        "fname": "jack",
        "lname": "kelly",
        "email": "jack12@gmail.com",
        "city": "New York"
    }
]