How to Export Collection to CSV in Magento
Exporting data from your Magento store is a common requirement for marketing campaigns, price comparisons, and other business uses. In this post, we’ll guide you through the process of creating a cron job to export a collection to a CSV file.
Understanding Magento’s Export Process
Magento provides several built-in ways to export data:
- Admin Panel: The admin interface includes options to export products, customers, orders, etc.
- Dataflow Model: This is Magento’s core framework for importing and exporting data. It uses the
Mage_Dataflow_Model_Batchclass as a base for all import/export models. - Import/Export Module: Located at
app/code/core/Mage/ImportExport, this module contains the actual logic for reading/writing CSV files.
Step-by-Step Guide to Custom Export
Let’s create an export script that generates a CSV file containing product information:
- Create a new Model
In your custom module (e.g., Namespace_Modulename), create a new model at Model/Product/Export.php:
class Namespace_Modulename_Model_Product_Export extends Mage_Dataflow_Model_Batch
{
public function export()
{
$collection = Mage::getResourceModel('catalog/product_collection');
// Add filters or other modifications as needed
$fileName = 'path/to/your/file.csv';
$fileHandle = fopen($fileName, 'w');
foreach ($collection as $product) {
fputcsv(
$fileHandle,
[
$product->getId(),
$product->getSku(),
$product->getName(),
// Add other fields here
]
);
}
fclose($fileHandle);
}
}
- Create a Cron Job
Next, create a new cron job in app/code/core/Mage/Cron/Model/Observer.php or your custom cron module:
class Namespace_Modulename_Model_Cron_Model_Observer
{
public function exportProducts()
{
$exportModel = Mage::getModel('namespace_modulename/product_export');
$exportModel->export();
}
}
- Schedule the Cron Job
In your Magento admin panel, navigate to System > Configuration > Advanced > System > Cron:
- Set
Generate Schedules Everyto a suitable interval (e.g., 15 minutes). - Add a new job with the following details:
- Code: A unique identifier
- Run model: Namespace_Modulename_Model_Cron_Model_Observer::exportProducts
Conclusion and Best Practices
Exporting data from Magento is a common task that can be achieved using the built-in Dataflow framework. By creating a custom model and scheduling it as a cron job, you can automate regular exports of product information or any other collection.
Remember to:
- Be mindful of file permissions when writing to the filesystem.
- Add error handling to your export script.
- Test your exports thoroughly before scheduling them for production use.
For more advanced export requirements or if you’re looking to build a custom import/export solution, consider exploring the Laravel Company blog for tips on using Magento’s extension architecture and data management best practices.