How to create CSV file in PHP?

Create CSV file:

PHP fputcsv function help us for creating CSV file. It returns the length of the written string or false on failure.

Example:

<?php

$list = array (
    array('ID', 'Name', 'Email', 'Roll Number'),
    array('1', 'Amit', '789'),
    array('2', 'Gaurav', '790')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

Delete CSV file:

<?php
unlink('file.csv');
?>

Note: rmdir() function removes directory.

 

Download CSV

<?php

$mydata = array(
    array('Name', 'Email', 'mobile'),
    array('Gaurav', 'gaurav@example.com', '+9185569XXXXX'),
    array('Latika', 'latika@example.com', '+9185569XXXXX')
);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"my-data.csv\"");
outputCSV($mydata);

function outputCSV($data)
{
    $outstream = fopen("php://output", 'w');
    function __outputCSV(&$vals, $key, $filehandler)
    {
        fputcsv($filehandler, $vals, ',', ' ');
    }
    array_walk($data, '__outputCSV', $outstream);
    fclose($outstream);
}

Demo

Leave A Comment