Warning: Undefined array key "show" in /home/shtechno/public_html/shivamkhare.in/wp-content/themes/shivam/header.php on line 13
Warning: Undefined variable $bodyClass in /home/shtechno/public_html/shivamkhare.in/wp-content/themes/shivam/header.php on line 50
class="post-template-default single single-post postid-283 single-format-standard vertical">
close
Contact

Generate CSV and directly send to Mail WordPress

In this blog, you’ll learn how to generate CSV with database of WordPress and csv file directly send to mail as attachment.

This blog divide in two part 1st is Generate CSV and 2nd is attach to mail for send to user with the help of WordPress of PHP functions.

Generate CSV or URL

Copy the code from below and paste in your functions.php or file. For the path of updated CSV file use <?php echo create_csv(); ?>. This function update your dynamic data (values form databse) to CSV file.

function create_csv() {
    global $wpdb;  
    $filepath = '/path/report.csv';
    $fd = fopen($filepath, 'w');
    if($fd === FALSE) {
        die('Failed to open temporary file');
    }
    $records = $wpdb->get_results("SELECT * FROM `table_name`", ARRAY_A);
    fputcsv($fd, array('Field A', 'Field B', 'Field C'));
    foreach($records as $key => $value) {
        $modified_values = array(
            $value['field_a'],
            $value['field_b'],
            $value['field_c']
        );        
        fputcsv($fd, $modified_values);
    }
    rewind($fd);
    fclose($fd);
    return $filepath;
}

$wpdb (WordPress database access abstraction class)

$filepath = ‘/path/report.csv’; First you have to create black CSV file or download blank CSV file from here or upload in any folder in your server.

/path/: For path you can use $_SERVER[‘DOCUMENT_ROOT’] or copy “/nas/wp/www/sites/Your Theme Folder Name“.

Attach to mail

For send a mail in WordPress see : https://developer.wordpress.org/reference/functions/wp_mail/.

$to = 'shivamkhare02@gmail.com';
$subject = 'Generate report';
$headers = "From: Shivam Khare <no-reply@shivamkhare.in>\r\n";
$headers .= "Reply-To: no-reply@shivamkhare.in\r\n";
$headers .= "CC: cc@shivamkhare.in.in\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html>
<head>
  <title>List of New Price Changes</title>
</head>
<body><table><tr><td>MAKE</td></tr></table></body></html>";
$attachment = create_csv();
$sent = wp_mail($to, $subject, $body, $headers,$attachment);
if($sent) {
   echo 'message sent!';
}else{
   echo 'message not sent!';
}

$attachment = create_csv(); This is the code for assign path of updated CSV file to attachment variable of WordPress.