Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 343
stanparker Avatar asked Oct 11 '11 20:10

stanparker


3 Answers

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);
}
like image 125
aurora Avatar answered Oct 23 '22 14:10

aurora


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

$fp = fopen('users.txt', 'w');
if ($fp) {
   foreach ($users as $key => $value) {
       fputcsv($fp, array($key, $value));
   }
   fclose($fp);
} else {
   exit('Could not open CSV file')
}

See: fputcsv()

UPDATE - in the comments you're interested in how to read the file and get your users back out. Here's the return trip:

$users = array();
if (($handle = fopen("my-csv-file.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $users[$data[0]] = $data[1];
    }
    fclose($handle);
} else {
    exit('Could not open CSV file');
}
if (count($users) == 0) {
    exit('CSV file empty: no users found');
}
like image 43
artlung Avatar answered Oct 23 '22 15:10

artlung


Here's a solution using fputcsv() which flattens the key/value pairs to an array before writing to disk.

$filehandle = fopen("csvfile.csv", "w");

if ($filehandle) {
  foreach ($users as $key => $value) {
    fputcsv($filehandle, array($key, $value);
  }
  fclose($filehandle);
}
else // couldn't open file
like image 2
Michael Berkowski Avatar answered Oct 23 '22 16:10

Michael Berkowski