Tuesday, 8 May 2012

Create a comma separated csv from sql query


<?php
$select = "SELECT * FROM Your_table";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
    $header .= '"'.mysql_field_name( $export , $i ).'"';
 if($i != $fields-1)
 $header .= ",";
}
while( $row = mysql_fetch_row( $export ) )
{

    if(isset($row[0]) && $row[0] != ''){
  $row[0] = text_decrypt($row[0]);
 }
 $line = '';
    foreach( $row as $value )
    {                                           
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . ",";
        }
        $line .= $value;
    }

 $line = substr($line, 0, -1);
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                       
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_file_name.csv");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>

0 comments:

Post a Comment