PHP code to write to a CSV file from MySQL query

By: Jamie  

Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.

<?php
    function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {
        
        if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        }
        
        $result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );
        
        if($headers) {
            // output header row (if at least one row exists)
            $row = mysql_fetch_assoc($result);
            if($row) {
                fputcsv($fp, array_keys($row));
                // reset pointer back to beginning
                mysql_data_seek($result, 0);
            }
        }
        
        while($row = mysql_fetch_assoc($result)) {
            fputcsv($fp, $row);
        }
        
        fclose($fp);
    }

    // Using the function
    $sql = "SELECT * FROM table";
    // $db_conn should be a valid db handle

    // output as an attachment
    query_to_csv($db_conn, $sql, "test.csv", true);

    // output to file system
    query_to_csv($db_conn, $sql, "test.csv", false);
?>



Archived Comments

1. Ohyeahohyea
View Tutorial          By: Fre at 2017-01-25 11:37:08


Most Viewed Articles (in PHP )

A Basic Example using PHP in AWS (Amazon Web Services)

Counting Lines, Paragraphs, or Records in a File using pc_split_paragraphs() in PHP

How to make one else for two ifs in PHP

preg_replace() and preg_replace_callback() in PHP

Static Properties in PHP

Upload and Download files with FTP in PHP

Exception in module wampmanager.exe at 000F15A0 in Windows 8

PHP file upload prompts authentication for anonymous users

PHP file upload with IIS on windows XP/2000 etc

Resume or Pause File Uploads in PHP

PHP code to write to a CSV file for Microsoft Applications

Password must include both numeric and alphabetic characters - Magento

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Reading and Writing .gz files in PHP

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Latest Articles (in PHP)

Comment on this tutorial