Codeigniter export MySQL query results to CSV or XML in 5 lines

Codeigniter comes with lots of ready made libraries and classes which makes a developer’s life little bit easier.
Today we will see a very simple example to export MySQL query results, in fact any database results you are using, to CSV or XML using Codeigniter’s inbuilt libtary.

To achieve this we will is CI’s Database Utility Class. Here I am using Codeigniter 3, but this utility class is also available in old version like 2.x.

For this, we will use codeigniter’s database utility class library and download helper. Let’s quickly see at code:

Export Table results to CSV file:

Here is your export function in controller looks like:

Just call this function and you will get your export dump on browser.

You can also define your own delimiter and escape characters, and code for this will look like:

That’s it.

Export Table results to XML file:

In similar fashion, we can also export query result in XML format as follows:

Here for XML file we are just defining a document strucure and passing it in xml_from_result() method to generate xml.

Leave a Reply

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