5

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"
}
4
  • 1
    Into which issue did you run? And what is your code? Commented Oct 11, 2011 at 20:03
  • Well, I think that a lot of the help I found from other resources take the first row and make that the keys, and then take the values from the rest of the rows. I need some help getting the first column to be the key, the second column to be the value. Does that make sense? Commented Oct 11, 2011 at 20:05
  • Do you need the data in CSV? Or do you want to just json_encode() it? Commented Oct 11, 2011 at 20:05
  • I would prefer it in csv so that other members of my team can modify the access list if they need to using a text editor. Commented Oct 11, 2011 at 20:11

4 Answers 4

5

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is the right answer when combined with artlung's
I would simply omit the second parameter to fgetcsv(), since there's no reason a priori (in the spirit of a comment below from Eric) to suppose that the names are less than 4096 characters long.
@Peter: yes, you are right -- since php5 it's possible to omit the length parameter. i've adjusted my example according to it ...
3
$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');
}

2 Comments

This is the right answer when combined with harald's
I would simply omit the second parameter to fgetcsv(), since there's no reason a priori (in the spirit of a comment below from Eric) to suppose that the names are less than 4096 characters long.
2

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

1 Comment

And never forget close file with fclose($filehandle).
2

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.

4 Comments

Fails if the user is 'Parker, Stan'
My question is how to get it from CSV back into an array.
@Eric 'Parker, Stan' would require the comma to be encoded, of course. But there's nothing in the original question to suggest that this is necessary or even desirable. Still, your remark is a good one since the asker characterizes himself as a noob.
@stanparker I edited my answer to add some logic for reading CSV back into an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.