отправить электронное письмо экспортированный файл CVS PHP MySQL - PullRequest
1 голос
/ 07 февраля 2012

Я пытаюсь отправить по электронной почте экспортированный CSV-файл. Однако, когда я нажимаю на ссылку, появляется всплывающее окно для загрузки CVS с записью из MySQL. Как я могу отправить электронное письмо этот CSV-файл на специальный адрес электронной почты? Большое спасибо за помощь и идеи. с уважением. Вот мой код

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.';
    }

1 Ответ

0 голосов
/ 07 февраля 2012

OK. Сначала вы должны сохранить файл CSV. Если вы установили заголовки, как вы упомянули, файл будет автоматически загружен. Пожалуйста, прочитайте эту статью об этом.

http://us2.php.net/manual/en/function.fputcsv.php

После создания CSV-файла вы можете отправить его по электронной почте с помощью функции PHP mail. Если вам нужна библиотека, просто проверьте это. Это легко реализовать.

http://www.redvodkajelly.com/code/php-email-class/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...