Rabu, 26 Desember 2018

Export Joomla Database Table to CSV

Completed new component module to export table to csv file for Joomla 3.x.

In the template file, put this as submit button to initiate the export.

My component is called "com_testdata", so adjust accordingly.
The task value is "export_now", which is later captured by the component controller.

<form action="index.php" method="post" name="myForm" id="myForm" onsubmit="return submitbutton();" >


<input type="submit" name="export" class="btn btn-success" value="Export to CSV"/>

  <input type="hidden" name="task" value="export_now" /> 
  <input type="hidden" name="option" value="com_testdata" />

  <?php echo JHtml::_('form.token'); ?>
</form>

This is how the component controllers, below the switch task. It is calling a function called export_now():

$task = $this->input->getCmd('view', 'display');
switch ($task){


case 'export_now':
export_now();
break;

This is the export_now() function:

function export_now()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('id','message')));
$query->from($db->quoteName('#__testdata')); //change database
//validation
$query->where($db->quoteName('published') . ' = '. $db->quote('1'));
$query->where($db->quoteName('expired') . ' != '. $db->quote(null)); //article is not expired
$query->where($db->quoteName('expired') . ' > '. $db->quote(date('Y-m-d') ."\n")); //article is not expired
$query->where($db->quoteName('start') . ' != '. $db->quote(null)); //article is not null
$query->where($db->quoteName('start') . ' < '. $db->quote(date('Y-m-d') ."\n")); //article is started

//start query
$db->setQuery($query);
$results = $db->loadRowList(); // Row list, not objectlist.

$filename = 'user.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=datax.csv');
$output = fopen("php://output", "w") or die;
$headers = array('id','message');//set headers
fputcsv($output, $headers) or die;  // input headers to output

foreach ($results as $row){
fputcsv($output, $row) or die;
}

fclose($output) or die;
jexit();
}

The function above will extract only two columns from the database called "__testdata", they are "id" and "message". If you need more columns to be exported, then adjust the script accordingly.

Good luck.

Tidak ada komentar: