Create a gist now

Instantly share code, notes, and snippets.

Export WordPress Comments as Excel file. Uses PHPExcel, http://phpexcel.codeplex.com/. Place this file in the root of the WordPress installation. TODO: convert to plugin.
<?php
# Load slim WP
define( 'WP_USE_THEMES', false );
require( './wp-load.php' );
# http://phpexcel.codeplex.com/
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
global $wpdb;
$query = "SELECT * FROM $wpdb->comments
WHERE 1 = 1
AND ( comment_approved = '1' OR comment_approved = '0' )
ORDER BY comment_ID DESC";
$error = "Error: the query failed...
<pre style='width:700px;word-wrap:break-word;white-space:normal;'>$query</pre>";
$result = $wpdb->get_results( $query, ARRAY_A ) or wp_die( $error );
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("user")
->setLastModifiedBy("user")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 0;
// Sheet cells
$cell_definition = array(
'A' => 'comment_ID',
'B' => 'comment_post_ID',
'C' => 'comment_author',
'D' => 'comment_author_email',
'E' => 'comment_author_url',
'F' => 'comment_author_IP',
'G' => 'comment_date',
'H' => 'comment_date_gmt',
'I' => 'comment_content',
'J' => 'comment_karma',
'K' => 'comment_approved',
'L' => 'comment_agent',
'M' => 'comment_type',
'N' => 'comment_parent',
'O' => 'user_id'
);
// Build headers
foreach( $cell_definition as $column => $value )
$objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value );
// Build cells
while( $rowCount < count($result) ){
$cell = $rowCount + 2;
foreach( $cell_definition as $column => $value )
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $result[$rowCount][$value]);
$rowCount++;
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment