How to read CSV data as array pairs in Magento 2?

Read CSV file using Magento 2 to retrieve all the records from the CSV file used for fetch data of a specific entity.

You can Retrieve CSV file data as pairs by just calling Magento\Framework\File\Csv class. Csv.php class contains the getDataPairs() function to convert the first column as a key and second column as the value in the array from the CSV file.

This article is also useful when you submit the form with the CSV file as form post data, you can retrieve the CSV data by the $_FILES [‘tmp_name] Pass tmp_name from the Files Data to the getData($_FILES [‘tmp_name] ) function from the CSV Class to read each row of the file with an array of records.

Let’s assume your CSV file contains below value for the first column and a second column with comma-separated,

"Sort By","Sorting"
"Homepage","home"
"cc_type","Credit Card type"
"Shopping Options","Shop By"

We need to convert it into array pair using Magento 2.

<?php
namespace Rbj\CsvConvert\Block;

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

    /**
     * Retrieve data from file
     *
     * @return string[]
     */
    public function getFileData(): array
    {
        $data = [];
        $file = '/var/www/html/mage231/var/import/en_US.csv';
        if ($this->fileDriver->isExists($file)) {
            $this->csvParser->setDelimiter(',');
            $data = $this->csvParser->getDataPairs($file);
        }
        return $data;
    }

In the Block file, I have passed the CSV file path as $file variable. first, verify CSV exists or not, if file exists, convert it to an array and gives an output.

Call from template file,
echo $block->getFileData();

Output:

Array
(
    [Sort By] => Sorting
    [Homepage] => home
    [cc_type] => Credit Card type
    [Shopping Options] => Shop By
)