How to export a table to CSV using PHP?

2

I have a contact table, I would like to know how to export it to .csv using PHP?

    
asked by anonymous 17.03.2014 / 20:30

1 answer

6

The following function exports an array in PHP to a CSV file:

function array_para_csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

To download the generated file:

function cabecalho_download_csv($filename) {
    // desabilitar cache
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // forçar download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposição do texto / codificação
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

Example usage:

cabecalho_download_csv("nome_arquivo_" . date("Y-m-d") . ".csv");
echo array_para_csv($array);
die();

To just save to archive (thanks, @Bacco):

function array_para_csv(array &$array, $arquivo)
{
   if (count($array) == 0) {
     return null;
   }
   $df = fopen( $arquivo, 'w');
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
}
    
17.03.2014 / 20:33