Skip to content

PHP code snippet – How to export mysql data to csv through ?

<?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;
?>
See also  CSS code snippet - How to serve through go?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.