Create and Download a CSV File using PHP


Create and Download a CSV File using PHP

Demo Download

Today, in this tutorial, I will show you how to create and download a CSV file using PHP.

It is very common that you need to export your MySQL data into Excel CSV format either for reporting or for uploading into another database system.

In this tutorial, I will explain each steps about how to create a CSV file using PHP and how to download a CSV file using PHP.

Basically, we are going to perform two operations, creating a CSV file and forcing web browser to download that CSV file.

Steps of Creating and Downloading a CSV File using PHP

Follow the below steps to create and download a CSV file using PHP.

  1. Create an HTML Button to Download CSV
  2. Add CSS to Style Download Button
  3. Create and Download CSV using PHP

1. Create an HTML Button to Download CSV

Commonly, user needs to click on a button to download a CSV file, therefore I am also creating an HTML button to generate and download CSV file.

Create an index.php file and copy paste the below html in it.

<form action="" method="post">
    <input type="submit" value="Download CSV"  class="button">
</form>

2. Add CSS to Style Download Button

Now add some styles to our download button, just copy paste the below CSS in your stylesheet or in the head section of index.php.

body {
        margin:0px;
        font-family:Arial, Helvetica, sans-serif;
}
.button {
        font-family: Montserrat;
        font-weight: bold;
        color: rgb(255, 255, 255);
        font-size: 16px;
        background-color: rgb(0, 103, 171);
        width: 200px;
        height: 40px;
        border: 0;
        border-radius: 6px !important;
        cursor: pointer;
}

Although the above two steps are not mandatory but it is better to give a practical example therefore I am also creating a button to generate and download a CSV file using PHP.

3. Create and Download CSV using PHP

Now copy paste the below PHP script in the top of the index.php to create and download a CSV file.

<?php
// If form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $fields = array('id', 'name'); // CSV column headings
    $delimiter = ","; 
    $filename = "allphptricks.com-export-".date('Y-m-d-H-i-s').".csv"; 
    $f = fopen("php://output", "w");
    fputcsv($f, $fields, $delimiter);
    $array = array(
                array("id"=>1, "name"=>"Javed Ur Rehman"), // first row
                array("id"=>2, "name"=>"Syed Ahsan Kamal"), // second row
                array("id"=>3, "name"=>"Abdul Muqeet Arab") // third row
                );       
    foreach($array as $row){ 
        // Adding data into CSV
        $row_data = array($row['id'], $row['name']); 
        fputcsv($f, $row_data, $delimiter); 
    }
    fclose($f);
    // Telling browser to download file as CSV
    header('Content-Type: text/csv'); 
    header('Content-Disposition: attachment; filename="'.$filename.'";'); 
    exit();
}
?>

Although, I have commented where necessary but I would like to tell you what above PHP code is doing.

First it is checking if user has submitted the form then execute the script.

Then we define the column heading, file name and created an $array which is used in CSV as data.

You can also fetch data from your database, learn how to select data from database.

After that we are storing array values into the file, once all the data is saved in the file then we asked the browser that this is a CSV file and forced the browser to download this file.

That’s it.

Conclusion

I hope now you know how to create and download a CSV file using PHP, the process is very simple and PHP provides functions to achieve this in a real quick.

I try my best to explain things as simple as possible, if you still have any query feel free to ask me in the comment section below.

Demo Download

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook, Twitter and share it.

Facebook Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

Leave a Reply

Your email address will not be published. Required fields are marked *