Site icon MageComp Blog

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

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!

Exit mobile version