How to Download File from URL using PHP cURL

On 2/15/2018 Be the first to comment!

Hi! In this post, we will see how to download file from url using php curl. CURL is a great tool when it comes to remote communication. Using it, you can easily connect to a remote server and download files to your local machine. It allows to send http post request and get request in php as well.

Executing a basic curl request will simply return the data to the output stream. But we don't want that. Instead, we must assign it to a php variable, which we can write it to the disk. Using CURLOPT_RETURNTRANSFER is the easiest way to copy remote files to our own. But there is a problem with this method. Below we will see the right way to download remote files with curl.

php download file from url curl

PHP - Download File from URL using cURL:

To download files from the remote url with curl, you have to follow the below steps:

  1. Create a writable file stream
  2. Pass the file handle to curl
  3. This will make cURL write the content downloaded directly into the file.
  4. Close the file handle.

As I said earlier, using CURLOPT_RETURNTRANSFER will pose a problem when we download huge files. You'll easily exceed memory limits, given the entire data has to be read into the memory before writing it to disk. Even if you increase the limit, it's an unnecessary load on the server.

Simply passing the writable file stream to the curl will make it copy the contents of the file directly. For this we have to use the CURLOPT_FILE option.

Here is the code snippet to download files from the remote url.

<?php
$file_url = 'http://www.test.com/images/avatar.png';
$destination_path = "downloads/avatar.png";

$fp = fopen($destination_path, "w+");

$ch = curl_init($file_url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
$st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);

if($st_code == 200)
 echo 'File downloaded successfully!';
else
 echo 'Error downloading file!';
?>

This code will download the file contents from the given $file_url and copy it to the $destination_path. Make sure the destination folder has write permission so that the file is downloaded correctly.

Brief explanation of the functions we have used above,

  • fopen() - The function opens a file or url and returns the file pointer.
  • curl_init() - Initialize the curl session.
  • curl_exec() - It executes the given curl session.
  • curl_close() - Destroy an existing curl session.
  • CURLOPT_FILE - The option instructs curl to save the data returned to the given file.
  • curl_getinfo() - Returns the status details of the latest transfer.

For HTTPS Transfer:

If your file url contains 'https' instead of 'http', it is better to configure the SSL option in curl with this line,

curl_setopt($ch, CURLOPT_SSLVERSION, 3);
Read Also:

That explains about downloading file from url using php curl. With this method, you can download even large files from remote servers without running out of memory usage. Also make sure to include proper error handling in the production environment. I hope this tutorial is useful. Please share it on social media if you like it.

How to Create Treeview with Bootstrap and jQuery

On 2/12/2018 Be the first to comment!

Hi! Today let's see about creating treeview using bootstrap and jquery. A Treeview is a tree like representation of elements in a hierarchical structure. It offers a quick and easy navigation through websites. Although there are several jquery plugins available for tree view that simplify the task, I wanted something that works well with bootstrap.

And I found out a good library called 'Bootstrap Treeview'. It leverages the best of bootstrap framework and helps you display hierarchical tree structures using the JSON data set. You can do much more than a simple tree, like fetch data from the database and render a dynamic tree, make it collapsible, add icons, checkboxes and filters etc.

how to create treeview in bootstrap

Building Treeview with Bootstrap:

Now let's see how to add treeview in bootstrap. To build the menu, we need three different libraries,

  1. Bootstrap CSS
  2. jQuery
  3. Bootstrap Treeview

These libraries are available in the cdn, so you can load them directly on your projects without downloading. Here is the procedure.

Step-1) Load Stylesheets

First load the required style sheets into your html file. You need to link both 'bootstrap' and 'bootstrap treeview' css files.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />

Step-2) Load JavaScript Libraries

Next you have to load the java script files. Be sure to load jquery before tree view to avoid dependency issues.

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>

Step-3) Create Placeholder for Tree View

Next add an html container to work as a placeholder for the tree view. Just a div block would do.

<div id="myTree"></div>

Step-4) Define JSON Data Structure

Now define the JSON structure required to hold the hierarchical data that will be displayed on the tree view menu.

var treeData = [
    {
        text: "Parent-Item-1",
        nodes: [
            {
                text: "Child-Item-1",
                nodes: [
                    {
                        text: "Grandchild-Item-1"
                    },
                    {
                        text: "Grandchild-Item-2"
                    }
                ]
            },
            {
                text: "Child-Item-2"
            }
        ]
    },
    {
        text: "Parent-Item-2"
    },
    {
        text: "Parent-Item-3"
    },
    {
        text: "Parent-Item-4"
    },
    {
        text: "Parent-Item-5"
    }
];

Step-5) Render the Treeview

Finally, display the tree structure in the placeholder element we have created in Step-3. For that, bind the treeview() method to the 'div' container and pass the json data to it.

$('#myTree').treeview({
    data: treeData
});

Above script will produce a tree view similar to this,

bootstrap treeview example

Complete Script: index.html

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Treeview Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="col-sm-4">
        <div id="myTree"></div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        var treeData = [
            {
                text: "Parent-Item-1",
                nodes: [
                    {
                        text: "Child-Item-1",
                        nodes: [
                            {
                                text: "Grandchild-Item-1"
                            },
                            {
                                text: "Grandchild-Item-2"
                            }
                        ]
                    },
                    {
                        text: "Child-Item-2"
                    }
                ]
            },
            {
                text: "Parent-Item-2"
            },
            {
                text: "Parent-Item-3"
            },
            {
                text: "Parent-Item-4"
            },
            {
                text: "Parent-Item-5"
            }
        ];
        $('#myTree').treeview({
            data: treeData
        });
    });
    </script>
</body>
</html>

In our example we have built a basic tree. But the plug-in offers several options to customize the appearance and behavior of the menu. Like changing colors, adding icons, badges and hyperlinks to the node items. Check here to know more about customizing options.

Read Also:

It's a hassle-free way to build a hierarchical tree-view using the bootstrap treeview plug-in. It works well with Apps that use bootstrap. I hope this post is useful for you. Please don't forget to share it on social networks if you like it.

CodeIgniter Autocomplete Search from Database using AJAX Example

On 2/09/2018 Be the first to comment!

Hi! In this post, let's see how to autocomplete search from database using codeigniter and ajax. We are going to pull in live search thing something similar to Google search. As soon as you start typing in the textbox, the related suggestions will appear from the database. To implement this auto complete feature we need a jquery plugin called 'Select2'.

Select2 is an excellent plug-in that supercharges the regular select box with search functionality. It's really inappropriate to make the end user to skim through hundreds of options to pick just one. With Select2 the entire process is a breeze. It adds up a search filter to the dropdown (select box), thus populating results on fly with the help of ajax.

codeigniter autocomplete search from database ajax

AJAX Autocomplete Search from Database in CodeIgniter:

To implement the live autocomplete search in codeigniter, we need two JavaScript libraries, 1. jquery.js and 2. select2.js. Either download them or use from the cdn library just like I do in this demo.

Just follow the below steps and you'll be good.

Step-1) Create Database

For database, I'm going to use MySQL here. Create a dummy database, a table and some records to use in the example. Below is a sql file. Run the queries on mysql and it will take care of database creation.

CREATE `db_demo`;
USE `db_demo`;
CREATE TABLE IF NOT EXISTS `tbl_language` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `lname` varchar(50) NOT NULL,
  `lcode` varchar(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;

INSERT INTO `tbl_language` (`id`, `lname`, `lcode`) VALUES
(1, 'English', 'en'),
(2, 'Afrikaans', 'af'),
(3, 'Greek', 'el'),
(4, 'Finnish', 'fi'),
(5, 'Spanish', 'es');

Step-2) Create Model

We need a codeigniter model to handle the database transactions. So create a model file inside 'application' > 'models' folder. It contains the function getLanguage() to fetch language names from the database that match the search term entered by the user.

SearchModel.php

<?php
class SearchModel extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function getLanguage($str)
    {
        $this->db->select('id, lname as text');
        $this->db->like('lname', $str);
        $query = $this->db->get('tbl_language');
        return $query->result();
    }
}
?>

Step-3) Create Controller

Next create a controller file inside 'application' > 'controllers' folder. It contains two functions,

  1. index() - this is the default method that just loads the view file.
  2. search() - This function will be triggered during the ajax call. It receives the incoming search term ('q'), communicate with the model and get the results matching the search term, encode them to json and pass it back to the browser.

SearchController.php

<?php
class SearchController extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->database();
    }

    function index()
    {
        $this->load->view('SearchView');
    }
    
    function search()
    {
        $q = $this->input->get('q');
        $this->load->model('SearchModel');
        echo json_encode($this->SearchModel->getLanguage($q));
    }
}
?>

Step-4) Create View

This is the final step. Create a view file inside 'application' > 'views' folder. It contains all the front-end logic, including html markup, css and java script. Here is where we need to fire the ajax call. Just load the js libraries and bind the select2() method to the dropdown that requires auto complete feature.

SearchView.php

<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter Search from Database Example</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <h3>CodeIgniter Autocomplete Demo</h3>
    <select id="language" name="language" class="itemName form-control" style="width:300px" ></select>

    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    
    <script type="text/javascript">
    $('#language').select2({
        placeholder: '-Select Language-',
        minimumInputLength: 1,
        ajax: {
            url: "<?php echo base_url();?>index.php/SearchController/search",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        }
    });
    </script>
</body>
</html>

That's it! We have everything in place. It's time to test the search filter. Just run the controller and if everything is okay, you'll see a drop-down box. Start typing in the textbox and you will see the suggestions popping up below in a list.

ajax autocomplete search select2

With the plug-in, you can not only pull in the results from the database, but from other sources such as a remote REST API or just a local JS array.

Read Also:

That explains about implementing search from database in codeigniter and ajax. Most modern web apps uses autocomplete search and is a sure fire way to increase user experience. Every little detail counts! So make sure you implement it on your next project. I hope this tutorial is useful for you. Please share it on your social circle if you like it.

How to Post JSON Data with PHP cURL & Receive It?

On 2/05/2018 1 Comment so far

Hi! Here let's see how to post json data with php curl and receive the raw json sent. You can simply use PHP file_get_contents() to send HTTP GET request. But it's not the same case with HTTP POST. Fortunately PHP cURL makes the process very simple. With curl you can easily send HTTP requests. In case you don't know, 'cURL' is a library that let you communicate with web servers using different protocols such as http, https, ftp, telnet, file etc.

To use curl, you must install libcurl package on your server according to the version of PHP you use.

send http post json in php

In case you are not sure if curl is enabled on your machine or not, use this code to check it.

<?php echo (is_callable('curl_init') ? 'cURL is enabled' : 'cURL is disabled'); ?>

How to Post JSON with PHP cURL?

In order to send HTTP POST request with JSON data, you have to follow some steps and they are,

  1. Format JSON data correctly
  2. Attach JSON to the body of the POST request
  3. Set the right content type with HTTP headers
  4. Send the request.

The following is the PHP code to send json through POST request.

<?php
// url
$url = 'http://mydomain.com/api/users/create';

// json data
$data = array(
    'site' => 'mydomain.com',
    'account' => 'admin',
    'status' => 'true'
);
$json = json_encode($data);

// send post request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>

Here is the explanation for the functions & curl options we have used in the above script:

  • curl_init() - Initialize a curl session, takes up a parameter URL to send post request.
  • curl_setopt() - Set the curl options.
  • CURLOPT_POSTFIELDS - This option will set the data to the body of the http request.
  • CURLOPT_HTTPHEADER - Option to set http headers. It is important to define the right content type here, so that the remote server understands what we sent. To send json, the content type should be set to 'application/json'.
  • CURLOPT_RETURNTRANSFER - Setting this to TRUE will place the response from the remote server on $result variable instead of outputting it.
  • curl_exec() - Send the HTTP request.
  • curl_close() - Close the curl session.

Retrieve the Posted JSON:

Okay! We have sent json data via http post request. But what will happen at the receiving end? How should we retrieve the incoming json?

Well! In our example we have sent raw json data. This can be accessed through php's input stream. Below is the code to receive the json posted,

<?php
$output = file_get_contents("php://input");
echo $output;
?>

You can decode the json and process it as you want. Pretty simple!

Read Also:

That explains about posting json data and receiving it using PHP cURL. This is not very different from sending a regular POST request. However, we are doing it over HTTP here. Hopefully, this tutorial is useful for you. Please don't forget to share it with your friends.

jQuery Animated Typing Effect using Typed.js Plugin

On 2/01/2018 Be the first to comment!

Hi! Today, we are going to see an interesting tutorial, which is to animate typing effect using jquery typed.js plugin. Not all animations require the skill of a graphics artist. You can pull in some really cool animations just with jquery plugins. jQuery has its share of animation plugins and 'Typed.js' is one among them. It is simple, lightweight and let you add typing effect to web pages. The text will be typed literally character by character thus giving you the impression it is being typed on a terminal.

Come, let's see how to implement this typing effect on websites.

jquery animated typing effect typed.js example

Adding Animated Typing Effect in jQuery:

Typed.js is a jquery library to simulate the terminal typing effect that allows you to print plain text or html as if you were typing on the screen.

How to Use it:

First create a container to print the string.

<div id="container"></div>

Then call the function typed() on the container element that we have created and provide the string(s) to be printed.

$("#container").typed({
    strings: ["String1", "String2", "..."]
});

You can add more than one string separated by commas. And can even style the screen cursor with css like this,

.typed-cursor {
    // add styles here
}

Below is the complete demo to animate dynamic typing.

<!DOCTYPE html>
<html>
<head>
    <title>Animated Typing Effect in jQuery</title>
    <style type="text/css">
    div {
        margin: 0 auto;
        width: 60%;
        min-height: 150px;
        text-align: center;
        background: #222;
    }
    
    #board, .typed-cursor {
        font-size: 40px;
        color: #FFF;
    }
    </style>
</head>
<body>
    <div>
        <span id="board"></span>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
    <script src="https://cdn.bootcss.com/typed.js/1.1.7/typed.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#board").typed({
            strings: ["This is the test.", "Have a Good Day!!!"],
            typeSpeed: 30
        });
    });
    </script>
</body>
</html>

Running this script would produce something like this,

typed js demo

You can pass several options to the method typed() and control the way it behaves. Above we have used only two options,

  1. strings - Defines the array of strings to be typed.
  2. typeSpeed - Defines the writing speed in milliseconds.

Apart from these two options, there are several others which you can refer in the official documentation of the plugin.

Read Also:

That explains about creating animated typing effect with jquery and typed.js. In the demo, I have loaded both 'js' libraries from CDN, but you can download and use them from your own server. I hope you find it useful. Please share the post with your friends if you like it.

How to Resize Image and Create Thumbnail in CodeIgniter

On 1/29/2018 Be the first to comment!

Hi! Today we will see how to resize image and create thumbnail in codeigniter. This comes handy when you want to resize user avatar or profile images. Generally, shopping sites employ this method. Although they upload large product images, they'll create a thumbnail version of them and lists them in several categories. This will not only save bandwidth but load the page faster and listing more items in a limited space. We are going to see how to do this in codeigniter.

CI offers a very useful image manipulation class called image_lib which we are going to use for resizing the image. Using this library you can not only change the size but perform crop, rotate and watermark images. It is compatible with all major image libraries like GD/GD2, ImageMagick and NetPBM and we will use GD2 here.

codeigniter resize image and create thumbnail

CodeIgniter - Image Resizing and Creating Thumbnail Image:

Let's build a CI demo to implement image resizing and the process goes like this. The user uploads images using the upload form provided. The image will be uploaded and moved to the 'uploads' folder on the server. And the same will be resized to a thumbnail size image and stored inside the 'thumbnails' folder. We will add the appropriate notification and error handling to the demo.

As for this example, we need to create two files, a codeigniter controller and a view. Follow the below steps to build demo.

Read: How to Create and Delete Session in CodeIgniter

Step-1) Create Folders to Store Images

You need proper folder structure to store the uploaded and resized images. Go to your application root directory and create two folders, 1. 'uploads' and 2. 'thumbnails' inside the 'uploads' folder. Also make sure you have write permission enabled on the folders.

Step-2) Create View

Next create a view file inside 'application' > 'views' folder. This file will contain the image upload form. The form itself is quite basic, a file input and a submit button.

upload_view.php

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Image Resize and Thumbnail Creation Demo</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container">
    <div class="row well" style="background: none;">
        <?php echo form_open_multipart('upload_controller/upload_image');?>
            <legend>Choose Image to Upload</legend>
            <div class="form-group">
                <input type="file" name="imgfile" />
                <span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Upload Image" class="btn btn-warning btn-lg"/>
            </div>
        <?php echo form_close(); ?>
        <?php if (isset($success)) { echo $success; } ?>
    </div>
    <?php if(isset($filename)) { ?>
    <div class="row text-center well" style="background: none;">
        <h4>Original Image</h4>
        <img src="<?php echo base_url().'uploads/'.$filename; ?>">
    </div>
    <div class="row text-center well" style="background: none;">
        <h4>Thumbnail Image</h4>
        <img src="<?php echo base_url().'uploads/thumbnails/'.$filename; ?>">
    </div>
    <?php } ?>
</div>
</body>
</html>

Step-3) Create Controller

In this step, create a controller file inside the 'application' > 'controllers' folder. This contains three functions, 1. index() which is the default, 2. upload_image() that verifies the submitted image file and uploads it to the server 3. resize_image() that creates a thumbnail of the uploaded image and saves it inside the 'thumbnails' folder.

upload_controller.php

<?php
class upload_controller extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    // default function
    function index()
    {
        //load file upload form
        $this->load->view('upload_view');
    }

    // image upload function
    function upload_image()
    {
        // upload settings
        $config = array(
            'upload_path' => './uploads/',
            'allowed_types' => 'png|jpg|jpeg|gif',
            'max_size' => '1024'
        );

        // load upload class
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('imgfile'))
        {
            // case - failure
            $upload_error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_view', $upload_error);
        }
        else
        {
            // case - success
            $upload_data = $this->upload->data();
            $data['filename'] = $upload_data['file_name'];
            $this->resize_image($data['filename']);
            $data['success'] = '<div class="alert alert-success text-center">Image uploaded & resized successfully!</div>';
            $this->load->view('upload_view', $data);
        }
    }
    
    // image resize function
    function resize_image($filename)
    {
        $img_source = './uploads/' . $filename;
        $img_target = './uploads/thumbnails/';

        // image lib settings
        $config = array(
            'image_library' => 'gd2',
            'source_image' => $img_source,
            'new_image' => $img_target,
            'maintain_ratio' => TRUE,
            'width' => 128,
            'height' => 128
        );
        
        // load image library
        $this->load->library('image_lib', $config);
    
        // resize image
        if(!$this->image_lib->resize())
            echo $this->image_lib->display_errors();
        $this->image_lib->clear();
    }
}
?>

After resizing the image, the controller passes the image filename to the view, where the original and the resized image will be displayed below the upload form.

That's it. We have all the necessary files in place. Now run the controller and choose an image to upload. If everything goes right, you will see the uploaded and thumbnail image at the bottom of the form.

create thumbnail image in codeigniter

Please make sure you have the GD library installed and pass the file path to the source and target image for resizing and not the url of the image files.

Read Also:

That explains about resizing the uploaded image and creating thumbnail in codeigniter. The process is quick and simple. You can also upload multiple images at once in codeigniter and produce thumbnails. It would be easier if you want to resize a large set of images. I hope this tutorial is useful to you. Please share it on social networks if you like it.

How to Export MySQL Table to JSON File in CodeIgniter

On 1/25/2018 Be the first to comment!

Hi! In this tutorial, we will see how to export mysql table to json file in codeigniter. Data portability has become more important than ever and a necessary requirement for modern applications. Almost all web services uses JSON format to migrate data from one location to another. So, as a Web Developer, you must know to handle json and various types of applications like Web, Mobile etc.

Exporting mysql into json allows you to easily port data to different platforms. The whole process is quite simple. Just fetch the data from mysql database, covert the query result to json and then write it in a file.

codeigniter export mysql table to json file

CodeIgniter - Export MySQL Table to JSON File:

Let's create a demo for exporting the database as json. The steps are easy to follow and we possibly need two files, a model and a controller.

Step-1) Create Database

We need a dummy database to use in the example, a database, a table and some sample records.

Run the below sql file in the mysql environment and create them.

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, 'Jim', 'Connor', 'jimconnor@yahoo.com', 'Las Vegas'),
(2, 'Taylor', 'Fox', 'taylorfox@hotmail.com', 'San Francisco'),
(3, 'Daniel', 'Greyson', 'danielgreyson@hotmail.com', 'New York'),
(4, 'Julia', 'Brown', 'juliabrown@gmail.com', 'Los Angeles'),
(5, 'Rose', 'Harris', 'roseharris@gmail.com', 'New York');

Step-2) Create Model

In this step, create a model file in the 'application/models' folder. This will fetch data from the 'users' table, encode and return it as json to the controller.

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

Step-3) Create Controller

Finally, create a controller file in the 'application/controllers' folder. This will communicate with the model, retrieve the json data and write in into a file.

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...';
    }
}
?>

Now we have all the required files in place. Run the controller, this will export the mysql data to a json file and show you a success message if all goes well.

You can check for the file 'user_data.json' inside the root directory. This is the exported file I received.

user_data.json

[
    {
        "id": "1",
        "fname": "Jim",
        "lname": "Connor",
        "email": "jimconnor@yahoo.com",
        "city": "Las Vegas"
    },
    {
        "id": "2",
        "fname": "Taylor",
        "lname": "Fox",
        "email": "taylorfox@hotmail.com",
        "city": "San Francisco"
    },
    {
        "id": "3",
        "fname": "Daniel",
        "lname": "Greyson",
        "email": "danielgreyson@hotmail.com",
        "city": "New York"
    },
    {
        "id": "4",
        "fname": "Julia",
        "lname": "Brown",
        "email": "juliabrown@gmail.com",
        "city": "Los Angeles"
    },
    {
        "id": "5",
        "fname": "Rose",
        "lname": "Harris",
        "email": "roseharris@gmail.com",
        "city": "New York"
    }
]
Read Also:

Likewise you can export the mysql table to the json file using codeigniter. The entire process is same as what you do with core php, but some may find it difficult to shift the code to fit with mvc pattern. And I hope this tutorial has clarified it. Please don't forget to share the post in social media if you like it.

Contact Form

Name

Email *

Message *