2

This is my code to fetch data from database table

$sql = "select * from tbl_input_values where 1";
$result = mysql_query($sql);
$resultRows = mysql_num_rows($result);

The below is the header that I used to download file as excel format:

header("Content-Type: application/vnd.ms-excel");   
header("Content-Disposition: attachment; filename=test.xls");

header("Pragma: no-cache");
header("Expires: 0");

And my code to fetch the record is as follows:

if($resultRows>0){
    $sep = "\t"; //tabbed character
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
        echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++){
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t"; 
        print(trim(str_replace(',', " ", $schema_insert)));
        print "\n";
    }
}

The code is working fine.

So now I have to email this attachment instead of downloading it. Means when user want to create excel file the excel will be emailed to given email id.

So what would be the better way to use email functionality?

Shimon Rachlenko
  • 5,469
  • 40
  • 51
Dinesh
  • 175
  • 3
  • 16
  • possible duplicate of [Data export to excel & save directly to the directory (folder)](http://stackoverflow.com/questions/8890300/data-export-to-excel-save-directly-to-the-directory-folder) – Rikesh Mar 14 '13 at 09:30
  • well instead of printing you write that in a file and then attach it as an attachment – TigerTiger Mar 14 '13 at 09:31
  • Does this answer your question? [Send attachments with PHP Mail()?](https://stackoverflow.com/questions/12301358/send-attachments-with-php-mail) – Nico Haase May 27 '21 at 20:04

2 Answers2

0

Possible It can help you ....

if($resultRows>0){
$sep = "\t"; //tabbed character
for ($i = 0; $i < mysql_num_fields($result); $i++) {
    echo mysql_field_name($result,$i) . "\t";
}
print("\n");
while($row = mysql_fetch_row($result)){
    $schema_insert = "";
    for($j=0; $j<mysql_num_fields($result);$j++){
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
    $schema_insert .= "\t"; 
    print(trim(str_replace(',', " ", $schema_insert)));
    print "\n";
}

 file_put_contents('$path_to_excelfile', $schema_insert);
  }

$to = 'youraddress@example.com';

     $subject = 'Test email with attachment';

     $random_hash = md5(date('r', time()));

     $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";

     $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

     $attachment = chunk_split(base64_encode(file_get_contents('path to file')));

   mail( $to, $subject, $message, $headers ); 

REF http://webcheatsheet.com/PHP/send_email_text_html_attachment.php

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
0
**Code to create excel in php:**
$dtime=date('Y-m-d H-i-s');
$dtimeFile=date('Y-m-d-H-i-s');
$headerTab ="Col1 \t Col2\t Col3\n";
$rowRecords='';
$rowRecords .=preg_replace("/\r|\n|\t/"," ",$Col1)."\t".preg_replace("/\r|\n|\t/", " ",$Col2)."\t".preg_replace("/\r|\n|\t/", " ",Col3). "\t\n";
date_default_timezone_set('America/Los_Angeles');
$filename="Your File Name-".$dtimeFile.".xls";
$path='/pathOfFile/';
$csv_handler = fopen ($path.$filename,'w');
fwrite ($csv_handler,$headerTab);
fwrite ($csv_handler,$rowRecords);
fclose ($csv_handler);

**Code to send html email with attached excel in php:**
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$headers = "From: from@gmail.com"."\r\n";
$headers.= "Bcc: bcc@gmail.com"."\r\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$headers .= "This is a multi-part message in MIME format.\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-type:text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$headers .= $msg."\r\n\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$headers .= $content."\r\n\r\n";
$headers .= "--".$uid."--"; 

$date=date("Y-m-d");
if(mail($to,"Mail heading--".$date,$msg,$headers)){
    echo "Mailed successfully";
}
else
{
    echo "Mailed couldn't be sent"; 
}