Skip to content

Instantly share code, notes, and snippets.

@neilbradley
Created July 18, 2017 13:07
Show Gist options
  • Save neilbradley/eca33950e34cc2b0f1dfa42471122400 to your computer and use it in GitHub Desktop.
Save neilbradley/eca33950e34cc2b0f1dfa42471122400 to your computer and use it in GitHub Desktop.
Product Feed / Export for Magento
<?php
/**
* Source: https://www.demacmedia.com/magento-commerce/magento-tutorials/magento-data-feed/
*/
/* To start we need to include abscract.php, which is located
* in /shell/abstract.php which contains Magento's Mage_Shell_Abstract
* class.
*
* Since this ProductExport.php is in /shell/Namespace/ we
* need to include ../ in our require statement which means the
* file we are including is up one directory from the current file location.
*/
require_once '../abstract.php';
class Namespace_ProductExport extends Mage_Shell_Abstract
{
protected $_io;
protected $_folder = 'exports';
protected $_name = 'ProductExport.csv';
protected $_delimiter = ',';
protected $_attributeMap = array(
'ProductName' => 'name',
'ProductPrice' => 'price'
);
protected function _construct()
{
$this->_io = new Varien_Io_File();
$this->_io->setAllowCreateFolders(true);
parent::_construct();
}
public function run()
{
$productsCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*');
$productsCollection->setPageSize(100);
$pages = $productsCollection->getLastPageNumber();
$currentPage = 1;
$this->_io->open(array('path' => $this->_folder));
$this->_io->streamOpen($this->_name);
$this->_io->streamWrite($this->_convertArrayToDelimitedString(array_keys($this->_attributeMap)) . "\r\n");
do {
$productsCollection->setCurPage($currentPage);
foreach ($productsCollection as $_product) {
$mappedValues = $this->_getMappedValues($_product);
if (!empty($mappedValues)) {
$this->_io->streamWrite($this->_convertArrayToDelimitedString($mappedValues) . "\r\n");
}
}
$currentPage++;
$productsCollection->clear();
} while ($currentPage <= $pages);
$this->_io->streamClose();
}
protected function _convertArrayToDelimitedString($data)
{
return implode($this->_delimiter, $data);
}
protected function _getMappedValues($product)
{
$data = array();
foreach ($this->_attributeMap as $column => $attribute) {
$data[] = $product->getData($attribute);
}
return $data;
}
}
// Create a new instance of our class and run it.
$shell = new Namespace_ProductExport();
$shell->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment