How To

How to Programmatically Export CSV File Category Name with Parent Category Name using Root Script in Magento 2?

Hello Magento Friends,

In this Magento 2 tutorial, we will discuss How to Programmatically Export CSV File Category Name with Parent Category Name using Root Script in Magento 2?’

In Magento 2, the ability to programmatically export data is a powerful feature that allows store owners and developers to manage large amounts of information efficiently. In this blog post, we will explore how to create a custom root script in Magento 2 to export a CSV file containing category names along with their parent category names. This can be particularly useful when performing bulk operations or generating reports involving category data.

Let’s get started,

Steps to Programmatically Export CSV File Category Name with Parent Category Name using Root Script in Magento 2:

Step 1: Create a file in your Magento root directory at the below path. 

magento_root_directory\Exportcategory.php

Then add the code as follows.

<?php
use Magento\MediaStorage\Helper\File\Storage\Database;
use Magento\Framework\AppInterface;

try
{
    require_once __DIR__ . '/app/bootstrap.php';
}
catch (\Exception $e)
{
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try
{
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=category_level.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');
   
    $categoryData = [];
    $rootCategoryId = 2; //Pass Root Category Id
    $categoryManagement = $objectManager->get('Magento\Catalog\Api\CategoryManagementInterface');
    $getSubCategory = getCategoryData($categoryManagement, $rootCategoryId);

    foreach ($getSubCategory->getChildrenData() as $category) {
        $cat = $category->getName();
        $categoryData[$category->getId()] = [
            'name' => $category->getName(),
            'url' => $category->getUrl()
        ];

        if (count($category->getChildrenData())) {
            $getSubCategoryLevelDown = getCategoryData($categoryManagement, $category->getId());
            foreach ($getSubCategoryLevelDown->getChildrenData() as $subcategorylist1) {
                $cat1 = $cat . ',' . $subcategorylist1->getName();
                $categoryData[$subcategorylist1->getId()] = [
                    'name' => $cat . ',' . $subcategorylist1->getName(),
                    'url' => $subcategorylist1->getUrl()
                ];
                if (count($subcategorylist1->getChildrenData())) {
                    $getSubCategoryLevelDownl = getCategoryData($categoryManagement, $subcategorylist1->getId());
                    foreach ($getSubCategoryLevelDownl->getChildrenData() as $subcategorylist2) {
                        $cat2 = $cat1 . ',' . $subcategorylist2->getName();
                        $categoryData[$subcategorylist2->getId()] = [
                            'name' => $cat1 . ',' . $subcategorylist2->getName(),
                            'url' => $subcategorylist2->getUrl()
                        ];
                        if (count($subcategorylist2->getChildrenData())) {
                            $getSubCategoryLevelDownl = getCategoryData($categoryManagement, $subcategorylist2->getId());
                            foreach ($getSubCategoryLevelDownl->getChildrenData() as $subcategorylist3) {
                                $cat3 = $cat2 . ',' . $subcategorylist3->getName();
                                $categoryData[$subcategorylist3->getId()] = [
                                    'name' => $cat2 . ',' . $subcategorylist3->getName(),
                                    'url' => $subcategorylist2->getUrl()
                                ];
                            }
                        }
                    }
                }
            }
        }
    }
    
    $output = fopen('php://output', 'w');
    fputcsv($output, array('Id', 'Level 1', 'Level 2', 'Level 3', 'Level 4'));
    foreach ($categoryData as $datak => $datav) {
        $catLevel = $datak . ',' . $datav['name'];
        $catLevel = explode(',', $catLevel);
        fputcsv($output, $catLevel);
    }

    fclose($output);
    exit;
}
catch(\Exception $e)
{
    print_r($e->getMessage());
}
function getCategoryData($categoryManagement, $categoryId)
{
    try {
        $getSubCategory = $categoryManagement->getTree($categoryId);
    } catch (Exception $exception) {
        $getSubCategory = null;
    }
    return $getSubCategory;
}

Step 2: After the above step, you will need to run the below-given URL.

https://yourdomain.com/Exportcategory.php 

Conclusion:

So now you know how to create a custom root script in Magento 2 to programmatically export category names along with their parent category names into a CSV file. Following these steps, you can efficiently manage category data and perform bulk operations in your Magento store. This script can be further customized and expanded to suit your specific needs, making it a valuable tool for any Magento 2 store owner or developer.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

7 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago