Wednesday, 26 February 2014

Export to CSV File - PHP

Export to CSV File - PHP

CSV is a simple file format that is widely used by IT Professional, business, and all who are familar with computer. Those who use computer in day to day life, they know how to use CSV/Excel. Among its most common uses is to move tabular data between programs that naturally operate on a more efficient or complete proprietary format. This file is easily readable even in mobile with use of some basic apps.

In Web Technology fileld,  number of times we have the send Stats, Logs and detail to our client in Form of CSV files.  Event may times we got the Text in form of excel/CSV Fle.

Now, Export the PHP data into CSV is very simple. Just  you need to do few simple steps.
  1. Save into into PHP multidimensional array
  2. Set the header
  3. Now, render the rows and then render EOL (First Row)
  4. Now, render the rows and then render EOL (Second Row)
  5. Now, render the rows and then render EOL  (Third Row and so on)
 Here EOL is End of Line.

Code Snippet
$lists = array(
    array(
        'Web', 'Technology', 'Experts', 'Notes',
    ),
    array(
        'Web1', 'Technology1', 'Experts1', 'Notes1',
    ),
    array(
        'Web2', 'Technology2', 'Experts2', 'Notes2'
    ),
    array(
        'Web3', 'Technology3', 'Experts3', 'Notes3',
    ),
    array(
        'Web4', 'Technology4', 'Experts4', 'Notes4',
    ),
    array(
        'Web5', 'Technology6', 'Experts5', 'Notes5',
    )
);

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv.csv");
header("Pragma: no-cache");
header("Expires: 0");

//header
echo  "Title1, Title2,Title3, Title4 \n";

foreach ($lists as $list) {
    echo implode(',', $list);
    echo PHP_EOL;
}