In this tutorial, Today I will explain to how to read CSV data as array in Magento 2. Sometimes, Developer need to read data and convert into array to manipulate data and use data in business logic.
For that, you need to use Magento\Framework\File\Csv class in your construct.
Let’s follow the below code for read csv data as array.
You may also like this :
- Add Category Filter to Product Grid in Magento 2 Admin
- Magento 2 : Remove decimals from quantity in product grid
<?php
/**
* Created By : Rohan Hapani
*/
namespace RH\Helloworld\Block;
use Magento\Framework\Exception\FileSystemException;
class ReadCsv extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
protected $file;
/**
* @var \Magento\Framework\File\Csv
*/
protected $csv;
/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Framework\Filesystem\Driver\File $file
* @param \Magento\Framework\File\Csv $csv
* @param \Psr\Log\LoggerInterface $logger
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Filesystem\Driver\File $file,
\Magento\Framework\File\Csv $csv,
\Psr\Log\LoggerInterface $logger,
array $data = []
) {
$this->file = $file;
$this->csv = $csv;
$this->logger = $logger;
parent::__construct($context,$data);
}
public function getCsvData()
{
$data = [];
$csvFile = '/var/www/html/m235/var/import/test_file.csv'; //Your CSV file path
try {
if ($this->file->isExists($csvFile)) {
$this->csv->setDelimiter(",");
$data = $this->csv->getDataPairs($csvFile);
return $data;
} else {
$this->logger->info('csv file is not exist');
return false;
}
} catch (FileSystemException $e) {
$this->logger->info($e->getMessage());
return false;
}
}
}
Here, you can pass delimiter inside setDelimiter() function which you want to set. Here, we use getDataPairs() function to convert csv data into array. After that, you can call getCsvData() function in your phtml file or anywhere and retrieve csv file data. If you want to use this code in your controller or any other file then, you can also use this code in any file.
That’s it !!!
I hope this blog is easy to understand about how to read CSV data as array in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.
Stay Safe and Stay Connected !!