Title: Function Array CSV Attachment
Last modified: June 3, 2017

---

# Function Array CSV Attachment

 *  [Van](https://wordpress.org/support/users/avgould/)
 * (@avgould)
 * [9 years ago](https://wordpress.org/support/topic/function-array-csv-attachment/)
 * Hi,
 * I’m currently working on a function that will be fired by a cron job. My issue,
   I’m sure will be the cron at some point but for the time being I’m struggling
   with the csv attachment.
 * The current function downloads the csv perfectly with the data and formatting.
   The attachment comes through but it’s a blank file.
 * Any insights would be greatly appreciated.
 *     ```
       unction weekly_lead_report($array_data, $filename){
   
         header('Content-Type: text/csv');
         header('Content-Disposition: attachment; filename="' . $filename . '"');
   
         $output = fopen('php://output', 'w');
         foreach($array_data as $row){
           fputcsv($output, $row, ',', '"');
         }
         fclose($output);
   
         $encoded = chunk_split(base64_encode($output));
   
       }
   
       function lms_lead_posts($posttypes){
   
         $args = array(
           'posts_per_page' => '-1',
           'post_status'    => 'publish',
           'orderby'        => 'date',
           'post_type'      => '',
   
           'date_query' => array(
               array(
                   'after' => '1 week ago'
               )
           )
   
         );
   
         $output = array();
         //DEFINE TITLES
         $titles = array('Date', 'Name', 'Phone', 'Email', 'License Status', 'Follow Up Date', 'Message');
   
         array_push($output, $titles);
   
         foreach($posttypes as $type) {
   
           $args['post_type'] = $type;
   
           $query = new WP_Query( $args);
   
           if ( $query->have_posts() ):
   
             while ( $query->have_posts() ): $query->the_post();
   
             //DEFINE DATA FIELDS
               $row = array( get_the_date('M j'),get_post_meta( get_the_id(),'lead_first_name', true ) . ' ' . get_post_meta( get_the_id(),'lead_last_name', true ),get_post_meta( get_the_id(),'lead_phone', true ),get_the_title(),get_post_meta( get_the_id(),'lead_re_school_status', true ),get_post_meta( get_the_id(),'lead_followup_date', true ),get_post_meta( get_the_id(),'lead_msg', true ) );
   
               array_push($output, $row);
   
               ob_end_clean();
   
             endwhile;
   
           endif;
   
           wp_reset_postdata();
   
         }
   
       weekly_lead_report($output, 'weekly_lead_report.csv');
   
         $weekly_send = new PHPMailer();
         $weekly_send->Debugoutput = 'html';
         $weekly_send->Host = "localhost";
         $weekly_send->SetFrom('noreply@somedomain.com', 'Some Name');
         $weekly_send->AddReplyTo('noreply@somedomain.com', 'Some Name');
         $weekly_send->AddAddress('somedude@somedomain.com', 'That Dude');
         $weekly_send->AddStringAttachment($output, 'weekly_lead_report.csv');
         $weekly_send->Subject    = 'That Dudes Weekly Lead Report';
         $weekly_send->Body       = 'Your Some Dudes weekly lead report is attached';
         $weekly_send->send();
   
       }
   
       if( isset($_GET['lead_data']) ){
   
         $posttypes = array('leads');
   
         lms_lead_posts($posttypes);
   
   
         die();
       }
   
       if( isset($_GET['_get_posttypes']) ){
         $args = array(
            'public'   => true,
            '_builtin' => false
         );
   
         $posttypes = get_post_types($args);
         print_r($posttypes);
   
         die();
   
       }
       ```
   
 * _[moderator note: please put code in backticks. for larger snippets, please use
   gist.githumb.com and paste a link to it here.]_
    -  This topic was modified 9 years ago by [Steven Stern (sterndata)](https://wordpress.org/support/users/sterndata/).

Viewing 1 replies (of 1 total)

 *  [Jack](https://wordpress.org/support/users/jdabber/)
 * (@jdabber)
 * [9 years ago](https://wordpress.org/support/topic/function-array-csv-attachment/#post-9196055)
 * Hello,
 * I do recommend putting this code as a gist for other people in this forum. The
   lines are so long that you have to scroll right a lot.
    [https://gist.github.com/](https://gist.github.com/)
 * Just looking at your code and its format, I see maybe one issue with the format
   of your fputcsv() function at the top. I don’t think you need to loop through
   all values in the second parameter “$row”. The function is already expecting 
   the values to come in as an array. Take a look at the [function’s documentation](http://php.net/manual/en/function.fputcsv.php).
 * Thus you may want to try removing the foreach loop and directly use $array_data
   as the second parameter (assuming it is sanitized for security).
 * Side note: In my experience, PHP’s read and write functions like fputcsv() are
   notorious for passing and making the file even if it doesn’t have/see the information
   that it needs. Thus, be sure to turn on error logging and check the logs.
 * Your code would look more like:
 *     ```
       // foreach($array_data as $row) {  // loop commented out/not needed
          fputcsv($output, $array_data, ',', '"');
       // }
       ```
   
    -  This reply was modified 9 years ago by [Jack](https://wordpress.org/support/users/jdabber/).

Viewing 1 replies (of 1 total)

The topic ‘Function Array CSV Attachment’ is closed to new replies.

## Tags

 * [csv](https://wordpress.org/support/topic-tag/csv/)

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 2 replies
 * 1 participant
 * Last reply from: [Jack](https://wordpress.org/support/users/jdabber/)
 * Last activity: [9 years ago](https://wordpress.org/support/topic/function-array-csv-attachment/#post-9196055)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
