Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

PlaintextHelper

By: a guest on Apr 16th, 2010  |  syntax: PHP  |  size: 1.61 KB  |  views: 196  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2. /* Basic CakePHP helper to output plaintext content and prompt to save as file.
  3.  * Based on CSVHelper:
  4.  * http://bakery.cakephp.org/articles/view/csv-helper-php5
  5.  */
  6. class PlaintextHelper extends AppHelper
  7. {
  8.         var $filename;
  9.        
  10.         public function render($output = '', $filename = null)
  11.         {
  12.                 if (!empty($filename) && is_string($filename))
  13.                 {
  14.                         $this->setFilename($filename);
  15.                 }
  16.                 header ('Expires: Mon, 1 Apr 1974 05:00:00 GMT');
  17.                 header ('Last-Modified: ' . gmdate('D,d M YH:i:s') . ' GMT');
  18.                 header ('Pragma: no-cache');
  19.                 header('Content-disposition:attachment;filename='.$this->filename);
  20.                 header('Content-type: text/plain');
  21.                
  22.                 return $this->output($output);
  23.         }
  24.        
  25.         /**
  26.          * Sets the output filename. Automatically appends .txt if necessary.
  27.          *
  28.          * @param string $filename Filename to save as
  29.          * @access public
  30.          */
  31.         public function setFilename($filename)
  32.         {
  33.                 if (!empty($filename))
  34.                 {
  35.                         if (strtolower(substr($filename, -4)) != '.txt')
  36.                         {
  37.                                 $filename .= '.txt';
  38.                         }
  39.                         $this->filename = $filename;
  40.                 }
  41.         }
  42. }
  43.  
  44. // controller:
  45.  
  46. var $helpers = array('Plaintext');
  47.  
  48. // VERY contrived example:
  49.  
  50. public function text($id)
  51. {
  52.         $this->set(
  53.                 'data',
  54.                 $this->User->read(null, $id)
  55.         );
  56.         $this->set('filename', 'user_'.$id.'_'.date('Y-m-d').'.txt');
  57.         Configure::write('debug', 0);
  58.         $this->layout = 'ajax';
  59.         $this->viewPath = 'elements/users';
  60.         $this->render('txt_dump');
  61. }
  62.  
  63. // app/views/elements/users/txt_dump.ctp:
  64.  
  65. <?php
  66. if (isset($filename)) $plaintext->setFilename($filename);
  67.  
  68. echo $plaintext->render($data['User']['first_name'] . ' ' . $data['User']['last_name']);