18
Mar

[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:

  1. 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.
  2. Save the file as “web pages”, i.e.: FILENAME.htm
  3. Open the htm file with your favorite text editor, you can see some html tags like “tr” and “td“, just like ordinary html files.
  4. Edit the file as you like, put your logic inside. The dummy data may help you out of some cycle, if/else condition.
  5. 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.

20
Dec

推荐

Propel,基于PHP5的ORMapping实现,包括一个generator和一个runtime的库,还不错:
http://propel.phpdb.org/

关于在一般的关系数据库(flat)中存贮树形结构的数据,这篇文章值得推荐:
http://www.sitepoint.com/print/hierarchical-data-database