[HowTo] Send smarty result page as attachment
Well I encounter this requirement while working on a small CMS. The customer wanna download the report page as attachment in MS-Excel format.
And here is the situation:
- All the web pages are built with smarty.
- The report page contains some logic that are already defined within the corresponding smarty template.
- I have access to PEAR install
So here is the solution I figured out:
- Create a new excel file, insert some dummy data, typically with one header row and two data row, and also a row with special format for empty dataset.
- Save the file as “web pages”, i.e.: FILENAME.htm
- Open the htm file with your favorite text editor, you can see some html tags like “tr” and “td“, just like ordinary html files.
- Edit the file as you like, put your logic inside. The dummy data may help you out of some cycle, if/else condition.
- Build the page with smarty, following is some pseudo code:
// some initial statement here, such as retrieving data ...
ob_start();
$smarty->assign(Smarty_Variable_In_Htm_File, $yourData);
//...
$smarty->display("FILENAME.htm“);$htmlResult = ob_get_contents();
ob_end_clean();$dl = new HTTP_Download();
$dl->setContentType(”application/vnd.ms-excel”);
$dl->setContentDisposition(HTTP_DOWNLOAD_ATTACHMENT, “ResultReportFile_”.date(’Ymd’).”.xls”);
$dl->setBufferSize(10 * 1024); // 100 K
$dl->setData($htmlResult);
$dl->setCache(false);
$dl->send();
One thing more, you have to install the “HTTP_Download” package from pear.php.net, together with all of its required dependency.
That’s all.