export data to csv in php
<?php
  
//store the data that you retrieve from DB in a varible, in my case its $keywords_analytics
  
if($keywords_analytics!=''){
    $delimiter = ",";
    $fileName = 'search_terms.csv';
    // Create a file pointer
    $f = fopen('php://memory', 'w');
    // Set column headers
    $fields = array('Date', 'Search Term', 'Total');
    fputcsv($f, $fields, $delimiter);
    foreach ($keywords_analytics as $ka){
        $lineData = array($ka['dated'], $ka['keyword'], $ka['total']);
        fputcsv($f, $lineData, $delimiter);
    }
    // Move back to beginning of file
    fseek($f, 0);
    // Set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $fileName . '";');
    //output all remaining data on a file pointer
    fpassthru($f);
}
exit;
?>