Export data in DB as CSV file (Store in system / Send it to Mail)

Export data in DB as CSV file (Store in system / Send it to Mail)


function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {

if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}

$result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );

if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}

while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}

fclose($fp);
}

// Using the function
$sql = "SELECT * FROM table";
// $db_conn should be a valid db handle

// output as an attachment
query_to_csv($db_conn, $sql, "test.csv", true);

// output to file system
query_to_csv($db_conn, $sql, "test.csv", false);

Close & Delete File

Close a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
//write some data here
fclose($handle);

Delete a File

$my_file = 'file.txt';
unlink($my_file);

Write & Append in a File

Write to a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);

Append to a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "\n".'New data line 2';
fwrite($handle, $new_data);

Create / Open a file

Create a File:

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot Create file:  '.$my_file); //if the file does not exist it creates file

Open a File:

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //if the file does exist it opens file