Exporting Component Data to a CSV File
There are times when we'd like to export the data saved in a component to a CSV file so it can be readily ported to other applications. The php class IAM CSV DUMP provides a simple way to output SQL query results as a CSV file.
To add this to your component, visit the link above at the PHP Classes website and download the file iam_csvdump.php. We'll store this in the component's helpers folder.
We can make this available at any point in our component by including this file in our admin.componentname.php file.
require_once (JPATH_COMPONENT_SITE.DS.'helpers'.DS.'iam_csvdump.php');
In our model, we'll add an export function
/**
* Export to CSV
*/
function export() {
$csvfile =& new iam_csvdump;
$query = $this->_buildExportQuery();
$this->_db->setQuery($query);
$query = $this->_db->getQuery();
$csvfile->dump($query, $filename, "csv", $databasename, $user, $password, $host );
exit;
}
And then add a custom button to the view
JToolBarHelper::custom('export', 'export', 'export', 'Export to CSV', false); Notice that in our custom button above, the second and third parameters indicate I'm using an image named export. This is in the images folder of my component and is referenced in the component's CSS file as
.icon-32-export {background-image: url(../images/export.png);}




We're gearing up to release our Recipe component this month. What can you look forward to?
