phpcsvthephpleague

LeagueCSV: undefined index on getRecords()


I'm trying to create users from a csv file in symfony. I'm using LEAGUECSV.

I get this error when I execute php ./bin/console doctrine:fixtures:load

Notice: Undefined index: FIRST_NAME

This is my fixture:

class UserFixture extends Fixture
{
    private $encoder;

    public function __construct(UserPasswordEncoderInterface $encoder)
    {
        $this->encoder = $encoder;
    }

    public function load(ObjectManager $manager)
    {

            $reader = Reader::createFromPath('%kernel.root_dir%/../src/CSVDATA/dbigo.csv');

            foreach ($reader->getRecords() as $result) {
                $user = New User();

                $user->setUsername($result['FIRST_NAME'].$result['LAST_NAME']);

                $user->setPassword(
                    $this->encoder->encodePassword($user,$result['NATREG'])
                );
                $user->setEmail($result['EMAIL']);

                $manager->persist($user);
            }
            $manager->flush();
       }
}


I tried using fetchAssoc but apparently that feature was deleted in the updated version of LEAGUECSV

My csv file have in the first column all the indexes


Solution

  • You need to specify a header offset if you want your records returned as an associative array: https://csv.thephpleague.com/9.0/reader/#csv-records

    $reader = Reader::createFromPath('%kernel.root_dir%/../src/CSVDATA/dbigo.csv');
    $reader->setHeaderOffset(0);
    
    foreach ($reader->getRecords() as $result) {
        // $result is now an associative array based on the header row
    }