Pages

Sunday, February 7, 2016

Export CSV File from your database records in wordpress

 global $wpdb;
 $edit_query = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."car_bookings");

$output_filename = 'MyReport.csv';
$output_handle = fopen( 'php://output', 'w' );

header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Content-Description: File Transfer' );
header( 'Content-type: application/csv' );
header( 'Content-Disposition: attachment; filename=' . $output_filename );
header( 'Expires: 0' );
header( 'Pragma: public' );   
ob_end_clean();

$first = true;
   // Parse results to csv format
   foreach ($edit_query as $row) {
    
      // Add table headers
      if($first){
         $titles = array();
         foreach($row as $key=>$val){
            $titles[] = $key;
         }
         fputcsv($output_handle, $titles);
         $first = false;
      }
     
       $leadArray = (array) $row; // Cast the Object to an array
       // Add row to file
       fputcsv( $output_handle, $leadArray );
   }

die();

No comments:

Post a Comment