如何在Magento中将Collection导出到csv?

时间:2012-02-08 12:06:51

标签: magento export-to-csv

我想制作一个cronjob来将一个集合导出到csv,用于ciao和kelkoo的价格比较。

我可以在Magento的核心看到一个例子吗?

我在下一个位置看到:

Mage/Dataflow/Model/Batch/export.php

但是这个文件什么都没找到。

也许可以看到如何工作:

Mage/importexport/

1 个答案:

答案 0 :(得分:4)

Mage_Adminhtml_Block_Widget_Grid::getCsv()Mage_Adminhtml_Block_Widget_Grid::getCsvFile()为例 以下是第一部分的相关部分作为示例(由我添加的评论)。

public function getCsv()
{
    $csv = '';
    $this->_isExport = true;
    $this->_prepareGrid(); // add the attributes to load, maybe required filters
    $this->getCollection()->getSelect()->limit(); // only unique records
    $this->getCollection()->setPageSize(0); // no paging, all records matching the set filters
    $this->getCollection()->load();
    $this->_afterLoadCollection(); // load additional data on the collection items if needed

    $data = array();
    // This foreach block adds headers to the columns
    foreach ($this->_columns as $column) {
        if (!$column->getIsSystem()) {
            $data[] = '"'.$column->getExportHeader().'"';
        }
    }
    $csv.= implode(',', $data)."\n";

    // $column is an instance of Mage_Adminhtml_Block_Widget_Grid_Column
    // Just a wrapper for getting the values from the collection items
    foreach ($this->getCollection() as $item) {
        $data = array();

        foreach ($this->_columns as $column) {
            if (!$column->getIsSystem()) {
                $data[] = '"' . str_replace(array('"', '\\'), array('""', '\\\\'),
                    $column->getRowFieldExport($item)) . '"';
            }
        }
        $csv.= implode(',', $data)."\n";
    }

    // Grid totals are only used by reports
    if ($this->getCountTotals())
    {
        $data = array();
        foreach ($this->_columns as $column) {
            if (!$column->getIsSystem()) {
                $data[] = '"' . str_replace(array('"', '\\'), array('""', '\\\\'),
                    $column->getRowFieldExport($this->getTotals())) . '"';
            }
        }
        $csv.= implode(',', $data)."\n";
    }

    return $csv;
}