How to create CSV files using PHP

| | 1 min read

Comma separated values, commonly referred to as CSV is one of the most popular methods for transferring data between systems. Creating code to export data to CSV is extremely useful in many applications. If you want to know how to create CSV files using PHP then read on.

Have a look at the PHP code shown below which can be used to to export data to csv file

    
      header("Content-type: text/csv");
      header("Content-Disposition: attachment; filename=file.csv");
      header("Pragma: no-cache");
      header("Expires: 0");
      $data = array(
          array("data12", "data16", "data17"),
          array("data2", "data33", "data25"),
          array("data31", "data32", "data23")
      );   
      $file = fopen('php://output', 'w');                              
      fputcsv($file, array('Description', 'Click', 'CTR'));      
      while ($data as $row) {
        fputcsv($file, $row);              
      }
      exit(); 
    
  

Code explained

The header function is used to send the raw HTML headers to the client. The argument Content-type: text/csv will set the content type, the content disposition header field will force the content to be saved as a file. The Cache control field is controlled using the Pragma header field. The expire header field determines the content is stale.

The $data array contains the CSV data which can be obtained using a simple MySQL query. (The MySQL query has been removed for simplicity). Now the function fopen(php://output) will create a file handler which will sent the data to the output stream. Finally the PHP function fputcsv will write the CSV data to a file.

I hope this article will give you an idea about how to create a csv file using PHP. Please use the comments below to give your feedback.