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

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

This article is helpful if you have a CSV file with only two columns and want to treat it as an array key-value pair.

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 an array pair using Magento 2.

<?php
declare(strict_types=1);

namespace Rbj\CsvConvert\Model;

use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\File\Csv;
use Magento\Framework\Filesystem\Driver\File;

class CsvToArray
{
    public function __construct(
        private readonly File $fileDriver,
        private readonly Csv  $csvParser
    ) {
    }

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

Output:

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