Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Generate and Download CSV file using array - php

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 572
    Comment on it

    Yesterday i was searching about how to generate and download csv file in php script using array, i google it and found lots of code there but nothing was working according to my requirement then developed this code. Feel free to let me know if you find any bug in the code.

    this is an array contain user details i.e. name & email id of users

    $results = array (

                    "0" => array
                    (
                        "name" => "Devendra Bhandari",
                        "email_id" => "devendr@gmail.com"
                    ),
                   "1" => array
                    (
                        "name" => "Ravi Sharma",
                        "email_id" => "ravi@gmail.com"
                    )
                );
    

    // File Name

    $filename = 'user_list.csv';

    // Set Header For CSV File

    header("Content-type: text/csv");

    header("Content-Disposition: attachment; filename=$filename");

    header("Pragma: no-cache");

    header("Expires: 0");

    // Generate CSV File

    generateDownloadCSV($results);

    function generateDownloadCSV($data)

    {

    $output = fopen("php://output", "w");
    
    $header = array_keys($data[0]); // Set all fields of first index of array as a header containing a list of field names for csv
    
    fputcsv($output, $header);
    
    foreach ($data as $row)
    {
        fputcsv($output, $row);
    }
    fclose($output);
    

    }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: