A simple code to export data to excel using PHP and cake php

Standard

A simple code to export data to excel using PHP and cake php

While generating a report in your project, you might have to download the data into excel file using PHP. In most scenario, you have to display the report in a page and create a link to download the report in the excel file. Well in that scenario, i think i can help you with a simplified code of PHP and cakephp.


Core Php

<?php
$filename =”excelreport.xls”;
$contents = “Name\t Email \t Mobile \t \n”;
$contents.= “Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n”;
$contents.= “Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n”;
$contents.= “Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n”;
header(‘Content-type: application/ms-excel’); /// you can set csv format
header(‘Content-Disposition: attachment; filename=’.$filename);
echo $contents;
?>

Cake php Code 
Past this code on controller
controlpanel_controller.php

class ControlpanelController extends AppController {
var $name=”Controlpanel”;
var $layout=false;

function file_export()
{
$this->autoRender=false;
ini_set(‘max_execution_time’, 1600); //increase max_execution_time to 10 min if data set is very large
$results = $this->ModelName->find(‘all’, array());// set the query function
foreach($results as $result)
{
$header_row.= $result[‘Doctor’][‘fname’].”\t”. $result[‘Doctor’][‘lname’] .”\t “.$result[‘User’][’email’].” \t \n”;

}
$filename = “export_”.date(“Y.m.d”).”.xls”;
header(‘Content-type: application/ms-excel’);
header(‘Content-Disposition: attachment; filename=”‘.$filename.'”‘);
echo($header_row);
}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s