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 Create a Shopify Draft Order in Shopify Remix Using GraphQL?

Shopify's Draft Orders feature is an essential tool for merchants, allowing them to create orders…

12 hours ago

How to Use CSS with Shopify Remix Vite?

CSS (Cascading Style Sheets) is essential in web development to create visually appealing and responsive…

1 day ago

Latest Hyvä Theme Trends to Elevate your Magento UI/UX

Your eCommerce website theme is highly important for your business's online success as it reflects…

2 days ago

Use Hyvä Products at their Full Potential

Hyvä represents more than just a theme; it is a comprehensive suite of extensions and…

2 days ago

Magento 2: Add Number of Products Displayed Per Page in Invoice PDF

Hello Magento mates, Invoices are critical documents in every eCommerce business, providing details of product…

4 days ago

Magento 2: How to Call phtml Based on Selection of Payment Method at Multishipping Payment

Hello Magento Friends, Multishipping in Magento 2 allows customers to split their orders into multiple…

7 days ago