How to Export Products with Category Names in Magento

category-productscollection;export

I'm trying to exports products programatically with their category names. Here is my code to export it.

 <?php
require_once 'app/Mage.php';
umask(0);

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);

$collection = Mage::getModel('catalog/product')
 ->getCollection()
 ->addAttributeToSelect('*'); 

foreach($collection as $product) {

  $_cat = array();
  $categoryName = array();

  foreach ($product->getCategoryIds() as $Id) {
    $_cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($Id);
  $categoryName = $_cat->getName();
  }
    fputcsv($output, array(
            $product->getSku(),
            $categoryName            
                     )
    );
}
?>

Products are associated to multiple categories. Though the code exports only one of the category names. How I can export all the category names associated to them programmatically?

Best Answer

The problem I see is that $product->getCategoryIds() returns an array, and you are using it later $Id to load the category. Also you can try this instead to load the categories for the store you want:

$rootId = Mage::app()->getStore($storeId)->getRootCategoryId();
$categories = Mage::getModel('catalog/category')
    ->getCollection()
    ->addFieldToFilter('path', array('like'=> "1/$rootId/%"));

$categories->count();
Related Topic