Magento – Export products by category name instead of category id

exportmagento-1.9

How can I export products by category name instead of category id?

enter image description here

Best Answer

<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_name');
$products->addAttributeToFilter('status', 1);//optional for only enabled products
$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
$fp = fopen('exports.csv', 'w');
$csvHeader = array("sku", "category_name");
fputcsv( $fp, $csvHeader,",");
foreach ($products as $product){
    $sku = $product->getSku();
    $categoryIds = implode('|', $product->getCategoryIds());//change the category separator if needed
    $_category = Mage::getModel('catalog/category')->load($categoryIds);
    $categoryData = $_category->getName();
    fputcsv($fp, array($sku, $categoryData), ",");
}
fclose($fp);

Put these code in root file and then run in browser it will create a csv file with category name

enter image description here

Related Topic