Вопрос

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.

Это было полезно?

Решение

<?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);
}

Другие советы

If you speak about the client's desktop, you can't using this way.

Anyway, why not giving your client a way to download your file?

Update: made a small improvment from Amado Martinez's answer

<?php
    $list = array (
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-type: text/csv');
    header("Content-Disposition: attachment;filename=file.csv");
    header("Content-Transfer-Encoding: binary");

    $fp = fopen('php://output', 'a');
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }
    fclose($fp);

?>

You cannot save to your desktop! Your browser runs in a sandbox, a sanitized environment that prevents access to the filesystem .

You script runs on server. Your file is on desktop. And even you got local server (like xamp, uniformserver etc) these are (and should be) also separated from your whole host filesystem. So the answer is - you cannot reach that unless you run your php script from command line on your host.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top