🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Read CSV File Using Root Script in Magento 2

By Sanjay JethvaUpdated on Mar 17, 2025 2 min read

Complete tutotial on using root script in Magento 2 to read data from CSV file.

If you are a Magento 2 developer, sometimes you may require to process records from a CSV file and add it to the Magento 2 database. In such case, you can use the Magento 2 root script to read data from the CSV file.

For an example, consider you have thousands of rows of data that you want to import into Magento 2. In such scenario, adding the data manually can be tedious and therefore you may require to use the Magento 2 root script to read the data from the CSV file.

Let’s go with the root script to read CSV file data in Magento 2!

How to Read CSV Data in Magento 2 Using Root Script?

In order to read the data from a CSV file in Magento 2, we’ll be using the fopen & fgetcsv functions in the root script. After opening the file, we’ll read each element of the file using the ‘for loop’ and close the file using the fclose, once the data reading is completed.

 <?php use Magento\Framework\App\Bootstrap; require 'app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
 
$open = fopen("my_csv.csv", "r"); // name of csv file
$data = fgetcsv($open, 1000, ",");
 
try{
 $handle = fopen("my_csv.csv", "r"); // name of csv file
 for ($i = 0; $data = fgetcsv($handle); ++$i) {
 if ($i == 0) {
 continue;
 }
 echo $data[$i];
 }
 fclose($handle);
}catch (\Exception $e) {
    print($e->getMessage());
}

That’s it!

This is how we can use the Magento 2 root script to read CSV file data. I hope this blog post will help through the same. In case you still have any queries or doubts, feel free to comment. I will be happy to help you.

Also, do not forget to share this Magento 2 tutorial with your Magento friends via social media.

Thanks for reading!

Also Read:

Sanjay Jethva Full Image
Article bySanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.