Search code examples
phpparsingcsvfgetcsv

CSV to Array PHP


I know there are a lot of resources out there for putting a CSV into an associative array, but I can't find anything that helps a noob like me do exactly what I want to do.

I currently have an associative array defined inside my PHP file:

$users = array(
    'v4f25' => 'Stan Parker', 
    'ntl35' => 'John Smith',
 );

I would like to move that array into a CSV file (users.txt) so:

 v4f25, Stan Parker
 ntl35, John Smith

The next step is to import users.txt so I can use it precisely like I was using the array $users.

Any help here? The last code I tried returned this: (which is not what I want)

 array(2) {
 ["v4f25"]=>
  string(5) "ntl35"
 ["Stan Parker"]=>
 string(10) "John Smith"
}

Solution

  • What about the following?

    $data = array();
    
    if ($fp = fopen('csvfile.csv', 'r')) {
        while (!feof($fp)) {
            $row = fgetcsv($fp);
    
            $data[$row[0]] = $row[1];
        }
    
        fclose($fp);
    }