Skip to content

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

//store the data that you retrieve from DB in a varible, in my case its $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
See also  PHP code snippet - How to pass variable in mysql laravel database?

Leave a Reply

Your email address will not be published. Required fields are marked *

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