Export To excel CSV

Posted: August 8, 2012 in Php
Tags: , ,

<?php
//
// establish database connection
//
$conn = mysql_connect( ‘hostname’, ‘username’, ‘password’ ) or die( mysql_error( ) );
mysql_select_db( ‘dbname’, $conn ) or die( mysql_error( $conn ) );
//
// execute sql query
//
$query = sprintf( ‘SELECT * FROM tablename’ );
$result = mysql_query( $query, $conn ) or die( mysql_error( $conn ) );
//
// send response headers to the browser
// following headers instruct the browser to treat the data as a csv file called export.csv
//
header( ‘Content-Type: text/csv’ );
header( ‘Content-Disposition: attachment;filename=filename.csv’ );
//
// output header row (if atleast one row exists)
//
$row = mysql_fetch_assoc( $result );
if ( $row )
{
echocsv( array_keys( $row ) );
}
//
// output data rows (if atleast one row exists)
//
while ( $row )
{
echocsv( $row );
$row = mysql_fetch_assoc( $result );
}
//
// echocsv function
//
// echo the input array as csv data maintaining consistency with most CSV implementations
// * uses double-quotes as enclosure when necessary
// * uses double double-quotes to escape double-quotes
// * uses CRLF as a line separator
//
function echocsv( $fields )
{
$separator = ”;
foreach ( $fields as $field )
{
if ( preg_match( ‘/\\r|\\n|,|”/’, $field ) )
{
$field = ‘”‘ . str_replace( ‘”‘, ‘””‘, $field ) . ‘”‘;
}
echo $separator . $field;
$separator = ‘,’;
}
echo “\r\n”;
}
?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s