CSV for Array PHP

I know that there are many resources for placing CSV in an associative array, but I can not find anything that helps a noob, like me, to 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 this array to a CSV file (users.txt) so that:

 v4f25, Stan Parker
 ntl35, John Smith

The next step is to import user.txt so that I can use it just like I used the $ users array.

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

 array(2) {
 ["v4f25"]=>
  string(5) "ntl35"
 ["Stan Parker"]=>
 string(10) "John Smith"
}
+5
source share
4 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);
}
+5
source
$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 - , , . :

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

( ):

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

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

, CSV :

php above_script.php > outfile.csv

, CSV , - :

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

:

  • ( ) , , , PHP - artlung .

  • RFC 4180 , ( ) CSV, CSV-/ .

+2

fputcsv(), / .

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

if ($filehandle) {
  foreach ($users as $key => $value) {
    fputcsv($filehandle, array($key, $value);
  }
  fclose($filehandle);
}
else // couldn't open file
+2

All Articles