简体   繁体   中英

PHP CSV from Associative Array

What I am having trouble with is creating an CSV file from an associative array in using PHP. My associative array is the result of a sqlsrv_fetch_array function.

When I run the code:

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
  echo '<pre>';
  print_r($row);
  echo '</pre>';
}

I can see:

Array
  (
  [Username] => User1
  [Password] => Password1
  [DisplayName] => UserOne
  [FirstName] => User
  [LastName] => One
  [Role] => Bacon
  [HomeEmailAddress] => UserOne@email.com
)
Array
(
  [Username] => User2
  [Password] => Password2
  [DisplayName] => UserTwo
  [FirstName] => User
  [LastName] => Two
  [Role] => Egg
  [HomeEmailAddress] => UserTwo@email.com
)
Array
(
  [Username] => User3
  [Password] => Pasword3
  [DisplayName] => UserThree
  [FirstName] => User
  [LastName] => Three
  [Role] => Sausage
  [HomeEmailAddress] => UserThree@email.com
)

All looking good. However the problem I am having is getting that into a CSV file. I want the file to look like

Username,Password,DisplayName,FirstName,LastName,Role,HomeEmailAddress
User1,Password1,UserOne,User,One,Bacon,UserOne@email.com
User2,Password2,UserTwo,User,Two,Egg,UserTwo@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com

I've been banging my head trying to get fputcsv working, using a foreach ($row as $key => $value) loop inside the while loop, but I am getting nowhere fast. Is this a futile quest? Can this be done on an array created using _sql_fetch_array_.

If I put the code in my where loop:

$fp = fopen('file.csv', 'w');

foreach ($row as $key => $value) {
 fputcsv($fp, $row);
}

fclose($fp);

I get a csv file with the output:

User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com

Any hints or suggestions would be greatly appreciated.

You need to combine the two sets of code you have ( ie read each row and then write the row out to your CSV.

$fp = fopen('file.csv', 'w');
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
 fputcsv($fp, $row);

}

fclose($fp);

The way you were doing it was just looking at a single row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM