I need to create a CSV file in PHP and that created file should be saved on local/server rather than asking to save.
Asked
Active
Viewed 2.7k times
5
-
just write the out put to a file instead of outputting to browser – Orangepill Jun 10 '13 at 13:10
-
1Could you clarify or provide more details please? I am interpreting your question as: "I have a server running PHP. I need generate a CSV file in PHP and save on the local filesystem." -- is that the correct interpretation? I guess I don't understand when you would be "asked to save." – cmt Jun 10 '13 at 13:10
-
Search is your friend - http://stackoverflow.com/questions/12398750/create-csv-file-using-php-and-save-it-into-directory – james_tookey Jun 10 '13 at 13:11
1 Answers
22
For the PHP versions later than 5.1.0 you can use the built-in CSV functions.
<?php
$data_array = array (
array ('col1','col2'),
array ('2','2'),
array ('3','6'),
array ('4','2'),
array ('6','5')
);
$fp = fopen('csvfile.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
This code will do the trick
$data_array = array (
array ('1','2'),
array ('2','2'),
array ('3','6'),
array ('4','2'),
array ('6','5')
);
$csv = "col1,col2 \n";//Column headers
foreach ($data_array as $record){
$csv.= $record[0].','.$record[1]."\n"; //Append data to csv
}
$csv_handler = fopen ('csvfile.csv','w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
echo 'Data saved to csvfile.csv';
but be sure about permission of csvfile so your script can create or write on it

Samy Massoud
- 4,295
- 2
- 35
- 48
-
@samyMassoud Does the `csvfile.csv` already have to exist on the server or are you creating this on the fly? – Tom Bird Sep 29 '14 at 14:43
-
`fopen` will create it on the fly , if it has permission over folder of this file – Samy Massoud Sep 30 '14 at 10:54