0
public function productDataToJson(Varien_Event_Observer $observer)
{
  $category = Mage::getModel('catalog/category');
  $tree = $category->getTreeModel();
  $tree->load();
  $ids = $tree->getCollection()->getAllIds();
  $jsonFilePath = Mage::getBaseDir().'/jsondata';
  foreach ($ids as $id) {
    $array = array();
    $products = $category->load($id)
        ->getProductCollection()
         ->addAttributeToSelect('*')
         ->addStoreFilter(Mage::app()->getStore()->getId());
    foreach ($products as $_product) {
        $array[] = array_merge($_product->getData(), array('category_ids' => $_product->getCategoryIds()));
    }
    $jsonData = Mage::helper('core')->jsonEncode($array);
    file_put_contents($jsonFilePath.'/c_' . $id . '_node.json', $jsonData);
  }
}

I have this function in an observer which creates a JSON file of all products in every category. I am trying to get the labels for the product attributes as well as the product price with appropriate currency. However, instead of getting the label I am getting the option ID.

How can I get the label for the attribute rather than the option ID, and the products price with the appropriate currency?

3 Answers 3

1

You could try this as well - IMO it's probably a lot more performant because of the fact that it's reducing the amount of queries being issued when generating your list. Let me know if you have any issues as I wasn't able to validate it.

public function productDataToJson(Varien_Event_Observer $observer)
{
    $categoryModel = Mage::getModel('catalog/category');
    $treeModel = $categoryModel->getTreeModel();
    $categoryIds = $treeModel->getCollection()->getAllIds();
    $file = new Varien_Io_File();
    $jsonData = [];

    $productCollection = Mage::getResourceModel('catalog/product_collection');
    $productCollection->joinField(
        'category_id', 'catalog/category_product', 'category_id',
        'product_id = entity_id', null, 'left'
    );

    $productCollection->addAttributeToSelect('*')
        ->addAttributeToFilter('category_id', [
            ['in' => $categoryIds]
        ]);

    /**
     * Collect all the products we need to generate the required JSON
     */
    foreach ($productCollection as $product) {
        $productData = $product->getData();

        foreach ($productData as $attrCode => $attrVal) {
            if ($attrText = $product->getAttributeText($attrCode)) {
                $productData[$attrCode] = $attrText;
            }
        }

        $jsonData[] = array_merge(
            $productData,
            [
                'category_ids' => $product->getCategoryIds()
            ]
        );
    }

    /**
     * Split the results back out into the format you need
     */
    foreach ($categoryIds as $categoryId) {
        $categoryProducts = [];
        array_filter($jsonData, function ($item) use($categoryId, &$categoryProducts) {
            if (array_search($categoryId, $item['category_ids']) !== FALSE) {
                $categoryProducts[] = $item;
            }
        });

        $jsonResult = Mage::helper('core')->jsonEncode($jsonData);

        $file->open([
            'path' => Mage::getBaseDir() . '/jsondata/'
        ]);

        $file->write('/c_' . $categoryId . '_node.json', $jsonResult);
    }
}
4
  • Error->Item (Mage_Catalog_Model_Product) with the same id "5" already exist .. :( Jul 20, 2017 at 8:56
  • 1
    Ah - that would be because of the join on catalog_category_product I believe, you could try modifying product_id in that query to be catalog_category_product.product_id = main_table.entity_id. Perhaps that will fix it, let me know. Otherwise I can try running this locally and debugging for you. Jul 21, 2017 at 19:06
  • Thanks @Daneil Kenney, but where and what exactly to write? Please do help ASAP. "Invalid attribute name: main_table.entity_id" Jul 22, 2017 at 9:18
  • Still got the error. :( Help ASAP. Jul 25, 2017 at 4:13
0
foreach ($products as $_product) {
    $array[] = array_merge($_product->getData(), array('category_ids' => $_product->getCategoryIds(),'price'=>Mage::helper('core')->currency($_product->getFinalPrice(), true, false),'size'=>$_product->getAttributeText('size'),'color'=>$_product->getAttributeText('color')));
}
1
  • Is this the answer to your question? I don't see any difference between this and the code example in your question. Edit: Nvm, I see what you did. Jul 20, 2017 at 6:08
0
  • Currently you are using $product->getData() to get all the product information.

  • However the product might be having some attributes with options e.g. multiselect, dropdown attributes

  • In order to get attribute label of product attribute you can use :

    $attrLabel = $_product->getAttributeText('attribute_code');

  • For example if you have a color attribute of 4 different options. When you call $product->getData() it will return the attribute option ID instead of it's label.

  • You have to use $attrLabel = $_product->getAttributeText('attribute_code'); to get the attribute option label

I hope this helps.

6
  • Ahsan I alos want dynamically created attribute lable text, How can I get this? Jul 22, 2017 at 10:46
  • Can you share any example ? I am unable to understand this scenario properly from your words. Jul 24, 2017 at 6:54
  • Ahsan, Eg. If I create brand as a dynamic attribute, then i want this attribute's lable in my json file. So that whenever I create dynamic attribute,i will able to get its lable to display and filter. Jul 24, 2017 at 6:59
  • @Ahsan, any solution for that? please do help ASAP. Jul 25, 2017 at 11:59
  • @SushantThorat While getting product's data, check product attribute types. And then get all attributes that are multiselect/Dropdown, and iterate through each attribute inside loop and get its labels as shown above. Jul 26, 2017 at 5:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.