Thursday, February 7, 2013

export data for CSV file using PHP


Exporting data to CSV file is handy work. Because most of the data users like to do their own filters and customisation activities. 
To export the data to CSV file we can use PHP header() function. It is totally the way you define header content type.
Here is sample
<?php
Header('content-type:text/csv’);
?>
Then required to define content disposition.  This is how do you going to present the data. I am try to export data as attachment file. And you have to provide file name too. My file name is example.csv.

header('Content-Disposition: attachment;filename=\example.csv');

Now you have to define CSV file rows, and columns. You can choose database data or other data. Here my sample.

$csvHeader = '"Col1","Col2"';
$csvData = '"Row1","Row1"';

Col1 and Col2 is top column of CSV file.

Now everything ready to present. This is  full sample code.
<?php

$csvHeader = '"Col1","Col2"';
$csvData = '"Row1","Row1"';

header('Content-type: text/csv');
header('Content-Disposition: attachment;filename=\example.csv');
echo $csvHeader . PHP_EOL;
echo $csvData;
?>

Here I used PHP_EOL to make end of line in CSV file first line.

Now lets see database data how to export. No magic there.

First connect to database. you can use separate file to put this code. 
<?php

// --------------------------------------------------------------
//fucntion for connecting mysql server
function conDb(){
$link = mysql_connect("localhost","root","password") or die("Can't Connect to the server");
mysql_select_db("mydb")or die("selecting database error");
}
// --------------------------------------------------------------
?>

This is sample code to export database data.
<?php
 header('Content-type:text/csv');//define content type
    header('Content-Disposition:attachment;filename=mysample.csv');//add file name
    $csvHeader = '"item1.","item2","item3"';//CSV file header coulum
    echo $csvHeader.PHP_EOL;
            $sql="SELECT item1,item2,item3 FROM mytable;//fetch data from database
$result = mysql_query($sql);
        while($row = mysql_fetch_array($result)){
            $csvData = $row['item1'].",".$row['item2'].",".$row['item3'];//table data
            echo $csvData.PHP_EOL;
        }
?>
Try this and enjoy. appreciated your comment.