stanparker
stanparker

Reputation: 216

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"
}

Upvotes: 5

Views: 4942

Answers (4)

Peter
Peter

Reputation: 2556

Try this (assuming your strings contain no commas):

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

foreach ($users as $k => $v) {
    print "$k, $v\n";
}

Obviously you could then create the CSV file like so:

php above_script.php > outfile.csv

Now, to get from CSV back into an array you could use something like:

$file = 'outfile.csv';

$arr = array();
if (file_exists($file)) {
    foreach (explode("\n", file_get_contents($file)) as $l) {
       list($k, $v) = explode(',', $l);
       $arr[trim($k)] = trim($l);
    }
}

print_r($arr, true);

NOTES:

  • If your strings do (or might) contain commas, then you'll probably want to use a PHP builtin function to decode them - in which case the answers by harald and artlung are useful.

  • RFC 4180 describes how commas (and other values) are encoded in CSV, in case you want to roll your own CSV encoding/decoding functions for whatever reason.

Upvotes: 2

aurora
aurora

Reputation: 9627

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);
}

Upvotes: 5

artlung
artlung

Reputation: 33833

$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');
}

Upvotes: 3

Michael Berkowski
Michael Berkowski

Reputation: 270767

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

Upvotes: 2

Related Questions