Php

Export Data to CSV and Download Using PHP and MySQL

In the previous tutorial, we learned How To Export Data to Excel, here in this article we will learn how to export data into CSV (comma-separated values) file and download it, CSV is a very common format for transferring tabular data between applications and databases.

You can also check other tutorials on Export Data with PHP,

Here, we have a sample result set from MySQL and want to export it in a CSV file.

Step 1: Create sample MySQL data in key-value pair.

$data = array(
 '0' => array('Name'=> 'Parvez', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
 '1' => array('Name'=> 'Alam', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
 '2' => array('Name'=> 'Sunnay', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
 '3' => array('Name'=> 'Amir', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
 '4' => array('Name'=> 'Amir1', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
 '5' => array('Name'=> 'Amir2', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);

Step 2: PHP code to get options type and force to browser download file instead of display.

Related Post
if(isset($_POST["ExportType"]))
{
  
    switch($_POST["ExportType"])
    {
  case "export-to-csv" :
            // Submission from
   $filename = $_POST["ExportType"] . ".csv";   
   header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
   header("Content-type: text/csv");
   header("Content-Disposition: attachment; filename=\"$filename\"");
   ExportCSVFile($data);
   //$_POST["ExportType"] = '';
            exit();
        default :
            die("Unknown action : ".$_POST["action"]);
            break;
    }
}
function ExportCSVFile($records) {
 // create a file pointer connected to the output stream
 $fh = fopen( 'php://output', 'w' );
 $heading = false;
 if(!empty($records))
   foreach($records as $row) {
  if(!$heading) {
    // output the column headings
    fputcsv($fh, array_keys($row));
    $heading = true;
  }
  // loop over the rows, outputting them
   fputcsv($fh, array_values($row));
   
   }
   fclose($fh);
}

Here we are setting header information to tell the browser that we are producing a CSV file and that the file should be offered for download.

Step 3: Define HTML layout for displaying data in table and button to fire export-to-csv action.

<div><a  (0)" id="export-to-csv">Export to csv</a></div>
 <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
            <input type="hidden" value='' id='hidden-type' name='ExportType'/>
            </form>
                  <table id="" class="table table-striped table-bordered">
                    <tr>
                        <th>Name</th>
                        <th>Status</th>
                        <th>Priority</th>
                        <th>Salary</th>
                  </tr>
                <tbody>
                  <?php foreach($data as $row):?>
          <tr>
          <td><?php echo $row ['Name']?></td>
          <td><?php echo $row ['Status']?></td>
          <td><?php echo $row ['Priority']?></td>
          <td><?php echo $row ['Salary']?></td>
          </tr>
          <?php endforeach; ?>
                </tbody>
              </table>

Step 4: Now we will use jQuery code to get the click event.

<script type="text/javascript">
$(document).ready(function() {
jQuery('#export-to-csv').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
 case 'export-to-csv' :
 $('#hidden-type').val(target);
 //alert($('#hidden-type').val());
 $('#export-form').submit();
 $('#hidden-type').val('');
 break
}
});
    });
</script>

Result:

I hope this helps you!.

Demo and Download Source Code Of Export to CSV

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

2 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

8 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

8 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

9 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

9 months ago

Categories