2012-02-07 20 views
1

我想發送電子郵件導出的csv文件。然而,當我點擊鏈接時,彈出一個下載帶有來自MySQL的記錄的CVS。我怎麼能發送電子郵件這個csv文件到特定的電子郵件地址?非常感謝幫助和想法。 此致敬意。 這裏是我的代碼發送電子郵件導出的cvs文件php mysql

header("Content-type: application/x-msdownload"); 
    header("Content-Disposition: attachment; filename=log.csv"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    $resultstr = array(); 
    foreach ($selectionlist as $result) 
     $resultstr[] = $result; 

    $ww=implode(",",$resultstr); 

    function escape_csv_value($value) { 
     $value = str_replace('"', '""', $value); // First off escape all " and make them "" 
     if(preg_match('/,/', $value) or preg_match("/\n/", $value) or preg_match('/"/', $value)) { // Check if I have any commas or new lines 
      return '"'.$value.'"'; // If I have new lines or commas escape them 
     } else { 
      return $value; // If no new lines or commas just return the value 
     } 
    } 


    $sql = mysql_query("SELECT * FROM article 
    WHERE idArticle in ($ww) ORDER BY idArticle DESC"); // Start our query of the database 

    $numberFields = mysql_num_fields($sql) or die('MySql Error' . mysql_error());; // Find out how many fields we are fetching 

    if($numberFields) { // Check if we need to output anything 
     for($i=0; $i<$numberFields; $i++) { 
      $keys[] = mysql_field_name($sql, $i); // Create array of the names for the loop of data below 
      $col_head[] = escape_csv_value(mysql_field_name($sql, $i)); // Create and escape the headers for each column, this is the field name in the database 
     } 
     $col_headers = join(',', $col_head)."\n"; // Make our first row in the CSV 

     $data = ''; 
     while($info = mysql_fetch_object($sql)) { 
      foreach($keys as $fieldName) { // Loop through the array of headers as we fetch the data 
       $row[] = escape_csv_value($info->$fieldName); 
      } // End loop 
      $data .= join(',', $row)."\n"; // Create a new row of data and append it to the last row 
      $row = ''; // Clear the contents of the $row variable to start a new row 
     } 
     // Start our output of the CSV 
     /*header("Content-type: application/x-msdownload"); 
     header("Content-Disposition: attachment; filename=log.csv"); 
     header("Pragma: no-cache"); 
     header("Expires: 0");*/ 
     echo $col_headers.$data; 

    } else { 
     // Nothing needed to be output. Put an error message here or something. 
     echo 'No data available for this CSV.'; 
    } 
+0

'$ selectionlist'從哪裏來?您的代碼中可能存在安全問題,採用SQL注入的形式。您應該閱讀相應的[PHP手冊頁](http://php.net/manual/en/security.database.sql-injection.php)。 – 2012-02-07 00:57:17

+0

要通過電子郵件發送CSV,您需要使用適當的電子郵件功能,而不是回顯數據。最簡單的方法是使用[Mail_Mime](http://pear.php.net/manual/en/package.mail.mail-mime.example.php)PEAR包,它可以讓您輕鬆地將CSV數據添加爲附件。或者,你必須自己編寫電子郵件,使用這樣的東西:http://www.finalwebsites.com/forums/topic/php-e-mail-attachment-script – 2012-02-07 01:03:16

回答