CSV Export functionality

<?php /** * @ CSV Export functionality * * 1.Establish Connection * 2.Select thr Database * 3.Fetching Data from the table * 4.Get total no. of the fields using mysql_num_fields * 5.Get the names of the fields through the loop using mysqli_fetch_field_direct * 6.The header() function sends a raw HTTP header to a client.To know more about the options please refer below links */ /** * 1.Establish Connection */ include_once('config.php'); /** * 2.Select thr Database */ $query = "SELECT * FROM student limit 50"; $header = ''; $data =''; /** * 3.Fetching Data from the table */ $export = mysqli_query ($connection, $query ) or die ( "Sql error : " . mysql_error( ) ); /** * 4.Get total no. of the fields using mysql_num_fields */ $fields = mysqli_num_fields ( $export ); /** * 5.Get the names of the fields through the loop using mysqli_fetch_field_direct */ for ( $i = 0; $i < $fields; $i++ ) { $header .= mysqli_fetch_field_direct($export, $i)->name . "\t"; } while( $row = mysqli_fetch_row( $export ) ) { $line = ''; foreach( $row as $value ) { if ( ( !isset( $value ) ) || ( $value == "" ) ) { $value = "\t"; } else { $value = str_replace( '"' , '""' , $value ); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim( $line ) . "\n"; } $data = str_replace( "\r" , "" , $data ); if ( $data == "" ) { $data = "\nNo Record(s) Found!\n"; } /** * 6.The header() function sends a raw HTTP header to a client.To know more about the options please refer below links */ header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=Export.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data"; ?>
All information are available in comment of snippet top.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.