Last active
February 19, 2016 19:51
-
-
Save EvanHerman/f8372583392ae7bf0ed0 to your computer and use it in GitHub Desktop.
Export a database table to .CSV. Usage example found at the bottom of this file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Export Class to help export a given database table to CSV. | |
*/ | |
class TOOL_EXPORT_CLASS { | |
/* | |
* Export our forms | |
* @parameters | |
* @table_name the name of the table to export | |
* @form_ids array of form ID's to export ie: array( 1,4,5,6 ) (user can select specific forms) | |
* @file_name the name of the exported file | |
*/ | |
public static function export_db_table_to_csv( $table_name, $form_ids , $file_name ) { | |
global $wpdb; | |
$wpdb->show_errors(); | |
if( is_array( $form_ids ) ) { | |
$results = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . $table_name . ' where ID in (' . implode( ', ' , $form_ids ) . ')' ); | |
} else { | |
$results = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . $table_name ); | |
} | |
// Process report request | |
if (! $results) { | |
$Error = $wpdb->print_error(); | |
die("The following error was found: $Error"); | |
} else { | |
// Set header row values | |
$output_filename = $file_name . '-'. date( 'm-d-Y' ) . '.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: text/csv' ); | |
header( 'Content-Disposition: attachment; filename=' . $output_filename ); | |
header( 'Expires: 0' ); | |
header( 'Pragma: public' ); | |
$first = true; | |
// Parse results to csv format | |
foreach ($results 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 ); | |
} | |
// Close output file stream | |
fclose( $output_handle ); | |
die(); | |
} | |
} | |
} | |
new TOOL_EXPORT_CLASS; | |
/** | |
* To use, you need to include this class file, then call the static export function | |
* Example: | |
* include_once get_stylesheet_directory() . '/lib/classes/class.export-db-entries.php'; | |
* TOOL_EXPORT_CLASS::export_db_table_to_csv( 'wp_users', $user_id_array, 'user-export' ); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment