title: Export sql postgres query to excel using php
body: <p>Hey guys I have this php application that i developing and i would like it to export the data correctly to the excel document such that each column header is exported with all the data in that column. This is what i have so far but its not working correctly as all the columns are shown in one row. How can i be able to achieve what i would like? Someone please assist me. This is the current implementation:</p>
  
  <pre><code>&lt;?php require_once('connections/pgconn.php');
  
  
  function cleanData(&amp;$str)
  {
  $str = preg_replace("/\t/", "\\t", $str);
  $str = preg_replace("/\r?\n/", "\\n", $str);
  if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }
  
  // filename for download
  $filename = "website_data_" . date('Ymd') . ".xls";
  
  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");
  
  $flag = false;
  $result = pg_query("SELECT to_char (a.CALLDATE,'yyyymm') as month,min(a.calldate) as      start_time,max(a.calldate) as end_time,
       ceil(SUM (a.CALLDURATION::integer) / 60) AS minutes,
       COUNT (DISTINCT a.IDENTIFIANT) AS distinct_callers,
  a.zoneiddest as country_code,b.country
  FROM cdr_data a,COUNTRY_CODES b
  WHERE  a.CALLSUBCLASS = '002'
       AND  a.CALLCLASS = '008'
  and a.zoneiddest::integer &gt; 0
  AND SUBSTR (a.CALLEDNUMBER, 1, 2) NOT IN
  ('77', '78', '75', '70', '71', '41', '31', '39', '76','79')
  
  and not substr(a.zoneiddest , 1 ,3) in ('254','255','256','211','257','250','256')
  and trim(a.zoneiddest)  = trim(b.country_code)
  GROUP BY to_char (a.CALLDATE,'yyyymm') ,a.zoneiddest,b.country
  ORDER BY 1") or die('Query failed!');
  
  while(false !== ($row = pg_fetch_assoc($result))) {
  if(!$flag) {
    // display field/column names as first row
    echo implode("\t", array_keys($row)) . "\r\n";
    $flag = true;
  }
  array_walk($row, 'cleanData');
  echo implode("\t", array_values($row)) . "\r\n";
  }
  exit;
  ?&gt;
  </code></pre>