Now a day, it is very common requirement of the clients, to have the data in CSV format and thus has become a routine work for the software developers. Though there is nothing difficult to create a csv file from the available data in php, but still many find it hard to make it downloadable from the server.
Create Downloadable CSV files Using PHP
Here is the complete code to first create csv from PHP array, place it on the desired path on the server and then make it downloadable.
example.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php $file = fopen("sample.csv", "a"); $student_info[0] = array("name" => "Ravi" , "age" => "15" , "class" => "metric"); $student_info[1] = array("name" => "Rahul" , "age" => "14" , "class" => "middle"); $student_info[2] = array("name" => "Viney" , "age" => "15" , "class" => "middle"); $student_info[3] = array("name" => "Kamal" , "age" => "16" , "class" => "metric"); $headers = 'NAME, AGE, CLASS'; // coloumn names for csv file fwrite($file,$headers); fwrite($file,"\r\n"); for($m=0;$m<=count($student_info); $m++) { if(isset($student_info[$m]) && $student_info[$m] != null) { fputcsv($file,$student_info[$m]); } } fclose($file); header('HTTP/1.1 200 OK'); header('Cache-Control: no-cache, must-revalidate'); header("Pragma: no-cache"); header("Expires: 0"); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=sample.csv"); readfile('C:\xampp\htdocs\test\sample.csv'); ?> |
Now you will get sample.csv as the resultant. So follow this example code to create downloadable CSV file using PHP
Check This Also:
How to Create an Website Visitor Counter with PHP
Create and Save XML file Using MySQL Data in PHP
How to Create Rss Feed Script Using PHP and MySQL
Thanks for reading the article.