Snippets

X-com M1 product / attribute export

You are viewing an old version of this snippet. View the current version.
Revised by Mycha de Vrees 577ee3e
<?php

require_once 'abstract.php';

class Mage_Shell_ExportProducts extends Mage_Shell_Abstract
{
    protected $connection;
    protected $header = true;
    protected $attributeSetModel = null;
    protected $images = [];
    /**
     * Run script
     *
     */
    public function run()
    {
        Mage::app()->setCurrentStore($this->getArg('store_id') ? $this->getArg('store_id') : Mage_Core_Model_App::ADMIN_STORE_ID);

        ini_set('memory_limit', '4096M');

        if ($this->getArg('file')) {
            $path = $this->getArg('file');
            echo 'writing data to ' . $path . PHP_EOL;
            $file = fopen($path, 'w');

            $productModel = Mage::getModel("catalog/product");
            $productCollection = $productModel
                ->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter(
                    'status',
                    array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                )
                ->joinField(
                    'qty',
                    'cataloginventory/stock_item',
                    'qty',
                    'product_id=entity_id',
                    '{{table}}.stock_id=1',
                    'left'
                )
                ->joinField(
                    'is_in_stock',
                    'cataloginventory/stock_item',
                    'is_in_stock',
                    'product_id=entity_id',
                    '{{table}}.stock_id=1',
                    'left'
                )
                // ->addFieldToFilter('entity_id', "4375")
                // ->addFieldToFilter(
                //     array('status'),
                //     array(
                //         array('in'=> array(
                //             'complete',
                //             'canceled',
                //             'closed'
                //         )),
                //     )
                // )
                ->setPageSize(100)
            ;

            $pages = $productCollection->getLastPageNumber();
            $i = 1;
            while($i <= $pages) {
                echo("Page: $i/$pages".PHP_EOL);
                $productCollection->setCurPage($i)->load();
                foreach ($producmdv0292
                tCollection as $product) {
                    try {
                        $this->exportData($product, $file);
                        $product = null;    
                    } catch(\Exception $e) {
                        var_dump($e->getMessage(), $product->getSku());
                    }
                }
                $i++;
                $productCollection->clear();
            }
            fclose($file);
            if ($this->getArg('images')) {
                // get images
                $images = array_unique($this->images);
                file_put_contents('images.txt', implode("\n", $images));
                echo("Images written to images.txt".PHP_EOL);
                // print_r($images);
            }
        } else {
            echo $this->usageHelp();
        }
    }

    protected function exportData(Mage_Catalog_Model_Product $product, $file)
    {
        /*
         * get dropdown attibutes using this query:
           select ea.attribute_code from eav_attribute ea where ea.attribute_id in (
            select distinct eao.attribute_id from eav_attribute_option eao where option_id in (select distinct eaov.option_id from eav_attribute_option_value eaov));
        *
        */
        $attributes = [
            "sku",
            "name",
            "description",
            "status",
            "short_description",
            "manufacturer_sku",
            "weight",
            "url_key",
            "type_id",
            "qty",
            "is_in_stock",
            "tax_class_id",
            "country_of_manufacture",
            "image",
            "featured_text",
            "visibility",
            "costprice",
            "price",
            "special_price",
            "alteanbol",
            "ean_bolcom",
            "proefperiode",
            "home_branded_product"
        ];
        $dropdownAttributes = [
            "color"
        ];

        $keys = array_merge($attributes, $dropdownAttributes);
        $productData = $product->getData();
        $data = [];
        foreach ($keys as $attributeCode) {
            if ($attributeCode == "image" && $productData[$attributeCode] != "no_selection") {
                $this->images[] = $productData[$attributeCode];
            }
            $data[$attributeCode] = $productData[$attributeCode] ?? "";
            if (in_array($attributeCode, $dropdownAttributes)) {
                // check if not "" or not null
                if ($data[$attributeCode]) {
                    $attributeValue = nl2br($product->getResource()->getAttribute($attributeCode)->getFrontend()->getValue($product));
                    $data[$attributeCode] = $attributeValue;
                    unset($attributeValue);
                }
            }
        }

        $data['category_codes'] = implode(';', $product->getCategoryIds());
        $data['simples_skus'] = "";
        $data['configurable_attributes'] = ""; // TODO uncomment when attributes are created in M2
        if ($product->getTypeId() == "configurable") {
            list($simplesSkus, $configurableAttributes) = $this->getSimpleSkus($product);
            $data['simples_skus'] = implode(',', $simplesSkus);
            // TODO uncomment
            //   comma implode because magmi explodes seperated by comma
            $data['configurable_attributes'] = implode(',', $configurableAttributes); // TODO uncomment when attributes are created in M2
        }
        
        $data['attributeset'] = $this->getAttributeSetName($product->getAttributeSetId());
        
        if($this->header) {
            fputcsv($file, array_keys($data), ';');
            $this->header = false;
        }
        fputcsv($file, $data, ';');

        unset($data);
        unset($product);

    }

    /**
     * Retrieve Usage Help Message
     *
     */
    public function usageHelp()
    {
        return <<<USAGE
Usage:  php -f export_data.php -- --file <csv_file>

  help                        This help
  file                        Csv file to write to

USAGE;
    }

    /**
     * @param $configurableProduct
     * return array
     */
    protected function getSimpleSkus($configurableProduct)
    {
        $simpleSkus = [];
        $configurableAttributes = [];
        $children = $configurableProduct->getTypeInstance()->getUsedProducts($configurableProduct);
        $_configurableAttributes = $configurableProduct->getTypeInstance()->getConfigurableAttributesAsArray($configurableProduct);
        foreach ($_configurableAttributes as $configurableAttribute) {
            $configurableAttributes[] = $configurableAttribute['attribute_code'];
        }
        foreach ($children as $childProduct) {
            $simpleSkus[] = $childProduct->getSku();
        }
        return [$simpleSkus, $configurableAttributes];
    }

    private function getAttributeSetName($attributeSetId)
    {
        if (!$this->attributeSetModel) {
            $this->attributeSetModel = Mage::getModel("eav/entity_attribute_set");
        }
        $this->attributeSetModel->load($attributeSetId);
        return $this->attributeSetModel->getAttributeSetName();
    }
}

$shell = new Mage_Shell_ExportProducts();
$shell->run();
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.