Create a download functionality in php

Create a download functionality in php

Php has a huge set of features to implement almost anything that you see across the internet. One of the common functionalities that you can find especially in dashboards is the functionality to download reports mainly in xls or csv format.

In this article I will show you how to implement this functionality using php and javascript/jquery. Here are the steps:

Suppose you have a table having user data which you want to download in a csv file. Here is the html of the table



<table class="user_table">
<thead>
  <tr>
   <th>Name</th>
   <th>Email Id</th>
   <th>Phone No</th>
   <th>City</th>
   <th>State</th>
  </tr>
</thead>
<tbody class="user_details_table_body">
 <tr>
   <td>Roshni</td>
   <td>roshni.devadiga@gmail.com</td>
   <td>86822223232323</td>
   <td>Mumbai</td>
   <td>Maharashtra</td>
 </tr>
 <tr>
   <td>Raj</td>
   <td>raj@gmail.com</td>
   <td>85656656556323</td>
   <td>Mumbai</td>
   <td>Maharashtra</td>
 </tr>     
</tbody>
</table>

Now create a download button. Clicking on this button will trigger the download of the above table. The html of the download button is as follows:



<div class="download_data_div">
    <a class="download_button">Download data in csv format</a>
</div>


Now we need to write the javascript that would trigger the download of the table. We will collect the data of the table in an array ‘myTableArray’ and pass it to the ‘download’ function. The download function will build a temporary form with action as ‘post’. It will add a hidden field in the form with value as the array data (‘myTableArray’) that you pass to the function. It will then submit the form to the php code that will have the download logic. In the same step it will remove the temporary form so that the user is on the same page and does not get redirected.

Here is the javascript code which we would bind to the download button

jQuery('.download_button').on('click', function(){
        var myTableArray = [];

        jQuery("table.user_table tr").each(function() {
            var arrayOfThisRow = [];
            var tableData = jQuery(this).find('td');
            if (tableData.length > 0) {
                tableData.each(function() {
                    arrayOfThisRow.push(jQuery(this).text());
                });
                myTableArray.push(arrayOfThisRow);
            }
        });
       
    download('<url>', 'table_data', myTableArray); //replace '<url>' with the url of the code that has the download logic
    });

Here is the actual download function in javascript

var download = function(url, key, data){
    // Build a form
    var form = jQuery('<form></form>').attr('action', url).attr('method', 'post');
    // Add the one key/value
    form.append(jQuery("<input></input>").attr('type', 'hidden').attr('name', key).attr('value', JSON.stringify(data)));
    //send request
    form.appendTo('body').submit().remove();
};

Now we need a code that will handle the download logic in php and send a csv file to the browser from the server containing the data that was sent in the array. Here we are simply fetching the input from the post data and iterating over it, extracting each row and writing it to a csv file.
Here is that php code:

$filename = "dashboard_report_" . date('Ymd') . ".csv";
  $fp = fopen('php://output', 'w');
  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-type: text/csv");
  $flag = false;
  foreach(json_decode(stripslashes($_POST['table_data'])) as $row) {
      if(!$flag)
      {
          fputcsv($fp, array('Name', 'Email id', 'Phone', 'City', 'State'), ',');
          $flag = true;
      }
    fputcsv($fp, $row, ',');
  }
  fpassthru($fp);

Hope this article has helped you. Please reach out to me in case you want any more details by commenting.

Comments are closed.