In this post I will explain to you how we can create a CSV (comma-separated value) file using simple PHP code. CSV file is very useful when we need to import and export data from the server or transfer data to other servers or in excel format. If you want to export data in excel you can read this post:- Import & Export data to Excel from MySQL using PHP.

Prerequisites

Before we start creating CSV with PHP, I hope you have a good basic knowledge of PHP.

Steps to create CSV with PHP

Step 1. Create a new PHP file in server.

Step 2. Now we need sample data to put in CSV file you can load data from a database or you can create a static array which contains sample data.

Step 3.  Now put that sample data in temp file using the below code.

Step 4. Now we need force browser to download CSV file using PHP Headers

Here is complete code to create a CSV file using PHP

Hope this code help you.