How to export a table to CSV using PHP?

Asked

Viewed 8,559 times

2

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

  • 3

    It would be interesting if you left your question more complete. What is the structure of your table? What is the DBMS?

1 answer

6

The following function exports a PHP array 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 of use:

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

To only save to file (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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.