How to read CSV data as array in Magento 2

In this Blog, we will see how to read csv data as an array with magento 2 csv class. let’s start…

<?php
namespace Mageclues\CsvReader\Block;

class Reader extends \Magento\Framework\View\Element\Template
{
    protected $_csvParser;
    protected $_fileDriver;
	
    public function __construct(
	\Magento\Framework\View\Element\Template\Context $context,
	\Magento\Framework\File\Csv $csvParser,
        \Magento\Framework\Filesystem\Driver\File $fileDriver,
        array $data = []
    ) {
	$this->_csvParser = $csvParser;
        $this->_fileDriver = $fileDriver;
        parent::__construct($context,$data);
    }

    /**
     * read data from csv file
     *
     * @return string[]
     */
    public function getCsvFileData()
    {
        $csvData = [];
        $csvFile = '/public_html/magento235/var/import/customer.csv';
		
		if ($this->_fileDriver->isExists($csvFile)) { 
			$this->_csvParser->setDelimiter(','); 
			$csvData = $this->_csvParser->getData($csvFile);

			  // to get array in key/value pair then use below function
			  // $csvData = $this->_csvParser->getDataPairs($csvFile);
		
			if (count($csvData) > 0) {
				foreach($csvData as $row => $data) {
					if ($row > 0) { // skip header row
						pritn_r($data);
					}
				}
			}
		} 
                else 
                {
                    $this->_logger->info('Csv file not exist at given path.');
                    return __('Csv file not exist at given path.');
                }
    }
}

We hope this technical blog helpful for you. please left comment if you have any question related to blog. thanks!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *