Brian Hunter
Brian Hunter

Reputation: 3

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] => [email protected]
)
Array
(
  [Username] => User2
  [Password] => Password2
  [DisplayName] => UserTwo
  [FirstName] => User
  [LastName] => Two
  [Role] => Egg
  [HomeEmailAddress] => [email protected]
)
Array
(
  [Username] => User3
  [Password] => Pasword3
  [DisplayName] => UserThree
  [FirstName] => User
  [LastName] => Three
  [Role] => Sausage
  [HomeEmailAddress] => [email protected]
)

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,[email protected]
User2,Password2,UserTwo,User,Two,Egg,[email protected]
User3,Password3,UserThree,User,Three,Sauage,[email protected]

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,[email protected]
User3,Password3,UserThree,User,Three,Sauage,[email protected]
User3,Password3,UserThree,User,Three,Sauage,[email protected]
User3,Password3,UserThree,User,Three,Sauage,[email protected]
User3,Password3,UserThree,User,Three,Sauage,[email protected]
User3,Password3,UserThree,User,Three,Sauage,[email protected]
User3,Password3,UserThree,User,Three,Sauage,[email protected]

Any hints or suggestions would be greatly appreciated.

Upvotes: 0

Views: 317

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

You need to combine the two sets of code you have ( i.e. 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.

Upvotes: 0

Related Questions