Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

please I have the following array :

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(6) "lkjhgj"
    [1]=>
    string(16) "[email protected]"
  }
  [1]=>
  array(2) {
    [0]=>
    string(5) "hgjk,"
    [1]=>
    string(18) "[email protected]"
  }
  [2]=>
  array(2) {
    [0]=>
    string(9) "dddd ffff"
    [1]=>
    string(13) "[email protected]"
  }
}

I want to put it into a csv file, so I've tried :

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

foreach ($list as $fields) 
{
   fputcsv($fp, $fields);
}

fclose($fp);

header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$fichier);

But when I download the file I found it empty !

Please masters any idea ? Thanks in advance

PS : Permissions are 777

share|improve this question
Where does $list come from in your code example? What's in there? – Pekka 웃 Feb 11 at 9:25
1  
I don't see any code that actually returns the file as part of the response! After you've closed the file it's got to be reopened before you can send it. Also I don't see any error checking in your code, fopen, fputcsv and other file operations can fail. You need to check that they've not returned FALSE – GordonM Feb 11 at 9:25
use $fp= fopen('php://output', 'w'); instead of $fp = fopen($fichier, 'w');.. see my answer below – Suhel Meman Feb 11 at 9:28
add comment (requires an account with 50 reputation)

2 Answers

up vote 3 down vote accepted
 $fichier = 'file.csv';
 header( "Content-Type: text/csv;charset=utf-8" );
 header( "Content-Disposition: attachment;filename=\"$fichier\"" );
 header("Pragma: no-cache");
 header("Expires: 0");

 $fp= fopen('php://output', 'w');

 foreach ($list as $fields) 
 {
    fputcsv($fp, $fields);
 }
 fclose($fp);
 exit();
share|improve this answer
thank you Suhel Meman, this works perfectly ! – Sami El Hilali Feb 11 at 10:24
add comment (requires an account with 50 reputation)

AS per your array structure, This is wrong :

foreach ($list as $fields) 
{
   fputcsv($fp, $fields);
}

Here $fields will be an array

Change it to

foreach ($list as $fields) 
{
   fputcsv($fp, $fields[0]);
   fputcsv($fp, $fields[1]);
}

NOTE : Don't forget to check your file permission. :D

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.