PHP How to convert array to csv using fputcsv function

please i have the following array:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(6) "lkjhgj"
    [1]=>
    string(16) "jhgjhg@jhgjj.com"
  }
  [1]=>
  array(2) {
    [0]=>
    string(5) "hgjk,"
    [1]=>
    string(18) "kjhgfghj@dgdfg.com"
  }
  [2]=>
  array(2) {
    [0]=>
    string(9) "dddd ffff"
    [1]=>
    string(13) "dddd@gmail.fr"
  }
}

      

I want to put it in a csv file, so I 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 upload the file, I found it empty!

Please comprehend any idea? thanks in advance

PS: Permissions: 777

+3


source to share


2 answers


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

      



+11


source


If you keep the array in session and encoded chars problems.



session_start();
$fp = fopen($_SESSION['CSV']['type'].'.csv', 'w');
foreach ($_SESSION['CSV'] as $fields) {
    $val1 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[0], ENT_QUOTES | ENT_XML1, 'UTF-8')));
    $val2 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[1], ENT_QUOTES | ENT_XML1, 'UTF-8')));
    $val3 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[2], ENT_QUOTES | ENT_XML1, 'UTF-8')));
    fputcsv($fp, array($val1,$val2,$val3,$val4,$val5));
}
fclose($fp);

      

0


source







All Articles