Search code examples
phpcsvdesktopfputcsv

Save a .csv file to desktop


I am developing a script using PHP to save a file to desktop as .csv file.

I found this code sample from PHP Manual.

<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>  

I created file.csv on my desktop. My issue is I cannot find the correct path to open the file on the desktop and, write and save. ($fp = fopen(‘file.csv’, ‘w’))

Should I have to show the path to server where I stored my web site and from there to to desk top's file.csv?

Can somebody guide me?

Thank you very much.


Solution

  • <?php
    $list = array (
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );
    header('Content-type: text/csv');
    header("Content-Disposition: attachment;filename=file.csv");
    
    // stream
    $f  =   fopen('php://output', 'a');
    foreach ($list as $fields) {
        fputcsv($f, $fields);
    }