Advertisement
Rukmal

php-export-data.php

May 3rd, 2012
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.92 KB | None | 0 0
  1. <?php
  2. // php-export-data by Eli Dickinson, http://github.com/elidickinson/php-export-data
  3.  
  4. /**
  5.  * ExportData is the base class for exporters to specific file formats. See other
  6.  * classes below.
  7.  */
  8. abstract class ExportData {
  9.     protected $exportTo; // Set in constructor to one of 'browser', 'file', 'string'
  10.     protected $stringData; // stringData so far, used if export string mode
  11.     protected $tempFile; // handle to temp file (for export file mode)
  12.     protected $tempFilename; // temp file name and path (for export file mode)
  13.  
  14.     public $filename; // file mode: the output file name; browser mode: file name for download; string mode: not used
  15.  
  16.     public function __construct($exportTo = "browser", $filename = "exportdata") {
  17.         if(!in_array($exportTo, array('browser','file','string') )) {
  18.             throw new Exception("$exportTo is not a valid ExportData export type");
  19.         }
  20.         $this->exportTo = $exportTo;
  21.         $this->filename = $filename;
  22.     }
  23.    
  24.     public function initialize() {
  25.        
  26.         switch($this->exportTo) {
  27.             case 'browser':
  28.                 $this->sendHttpHeaders();
  29.                 break;
  30.             case 'string':
  31.                 $this->stringData = '';
  32.                 break;
  33.             case 'file':
  34.                 $this->tempFilename = tempnam(sys_get_temp_dir(), 'exportdata');
  35.                 $this->tempFile = fopen($this->tempFilename, "w");
  36.                 break;
  37.         }
  38.        
  39.         $this->write($this->generateHeader());
  40.     }
  41.    
  42.     public function addRow($row) {
  43.         $this->write($this->generateRow($row));
  44.     }
  45.    
  46.     public function finalize() {
  47.        
  48.         $this->write($this->generateFooter());
  49.        
  50.         switch($this->exportTo) {
  51.             case 'browser':
  52.                 flush();
  53.                 break;
  54.             case 'string':
  55.                 // do nothing
  56.                 break;
  57.             case 'file':
  58.                 // close temp file and move it to correct location
  59.                 fclose($this->tempFile);
  60.                 rename($this->tempFilename, $this->filename);
  61.                 break;
  62.         }
  63.     }
  64.    
  65.     public function getString() {
  66.         return $this->stringData;
  67.     }
  68.    
  69.     abstract public function sendHttpHeaders();
  70.    
  71.     protected function write($data) {
  72.         switch($this->exportTo) {
  73.             case 'browser':
  74.                 echo $data;
  75.                 break;
  76.             case 'string':
  77.                 $this->stringData .= $data;
  78.                 break;
  79.             case 'file':
  80.                 fwrite($this->tempFile, $data);
  81.                 break;
  82.         }
  83.     }
  84.    
  85.     protected function generateHeader() {
  86.         // can be overridden by subclass to return any data that goes at the top of the exported file
  87.     }
  88.    
  89.     protected function generateFooter() {
  90.         // can be overridden by subclass to return any data that goes at the bottom of the exported file       
  91.     }
  92.    
  93.     // In subclasses generateRow will take $row array and return string of it formatted for export type
  94.     abstract protected function generateRow($row);
  95.    
  96. }
  97.  
  98. /**
  99.  * ExportDataTSV - Exports to TSV (tab separated value) format.
  100.  */
  101. class ExportDataTSV extends ExportData {
  102.    
  103.     function generateRow($row) {
  104.         foreach ($row as $key => $value) {
  105.             // Escape inner quotes and wrap all contents in new quotes.
  106.             // Note that we are using \" to escape double quote not ""
  107.             $row[$key] = '"'. str_replace('"', '\"', $value) .'"';
  108.         }
  109.         return implode("\t", $row) . "\n";
  110.     }
  111.    
  112.     function sendHttpHeaders() {
  113.         header("Content-type: text/tab-separated-values");
  114.     header("Content-Disposition: attachment; filename=".basename($this->filename));
  115.     }
  116. }
  117.  
  118. /**
  119.  * ExportDataCSV - Exports to CSV (comma separated value) format.
  120.  */
  121. class ExportDataCSV extends ExportData {
  122.    
  123.     function generateRow($row) {
  124.         foreach ($row as $key => $value) {
  125.             // Escape inner quotes and wrap all contents in new quotes.
  126.             // Note that we are using \" to escape double quote not ""
  127.             $row[$key] = '"'. str_replace('"', '\"', $value) .'"';
  128.         }
  129.         return implode(",", $row) . "\n";
  130.     }
  131.    
  132.     function sendHttpHeaders() {
  133.         header("Content-type: text/csv");
  134.         header("Content-Disposition: attachment; filename=".basename($this->filename));
  135.     }
  136. }
  137.  
  138.  
  139. /**
  140.  * ExportDataExcel exports data into an XML format  (spreadsheetML) that can be
  141.  * read by MS Excel 2003 and newer as well as OpenOffice
  142.  *
  143.  * Creates a workbook with a single worksheet (title specified by
  144.  * $title).
  145.  *
  146.  * Note that using .XML is the "correct" file extension for these files, but it
  147.  * generally isn't associated with Excel. Using .XLS is tempting, but Excel 2007 will
  148.  * throw a scary warning that the extension doesn't match the file type.
  149.  *
  150.  * Based on Excel XML code from Excel_XML (http://github.com/oliverschwarz/php-excel)
  151.  *  by Oliver Schwarz
  152.  */
  153. class ExportDataExcel extends ExportData {
  154.    
  155.     const XmlHeader = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
  156.     const XmlFooter = "</Workbook>";
  157.    
  158.     public $encoding = 'UTF-8'; // encoding type to specify in file.
  159.     // Note that you're on your own for making sure your data is actually encoded to this encoding
  160.    
  161.     public $title = 'Sheet1'; // title for Worksheet
  162.    
  163.     function generateHeader() {
  164.        
  165.         // workbook header
  166.         $output = stripslashes(sprintf(self::XmlHeader, $this->encoding)) . "\n";
  167.        
  168.         // Set up styles
  169.         $output .= "<Styles>\n";
  170.         $output .= "<Style ss:ID=\"sDT\"><NumberFormat ss:Format=\"Short Date\"/></Style>\n";
  171.         $output .= "</Styles>\n";
  172.        
  173.         // worksheet header
  174.         $output .= sprintf("<Worksheet ss:Name=\"%s\">\n    <Table>\n", htmlentities($this->title));
  175.        
  176.         return $output;
  177.     }
  178.    
  179.     function generateFooter() {
  180.         $output = '';
  181.        
  182.         // worksheet footer
  183.         $output .= "    </Table>\n</Worksheet>\n";
  184.        
  185.         // workbook footer
  186.         $output .= self::XmlFooter;
  187.        
  188.         return $output;
  189.     }
  190.    
  191.     function generateRow($row) {
  192.         $output = '';
  193.         $output .= "        <Row>\n";
  194.         foreach ($row as $k => $v) {
  195.             $output .= $this->generateCell($v);
  196.         }
  197.         $output .= "        </Row>\n";
  198.         return $output;
  199.     }
  200.    
  201.     private function generateCell($item) {
  202.         $output = '';
  203.         $style = '';
  204.        
  205.         if(preg_match("/^[0-9]{1,11}$/",$item)) {
  206.             $type = 'Number';
  207.         }
  208.         // sniff for valid dates should start with something like 2010-07-14 or 7/14/2010 etc..
  209.         elseif(preg_match("/^(\d{2}|\d{4})[\\\-]\d{1,2}[\\\-](\d{2}|\d{4})([^d].+)?$/",$item) &&
  210.                     ($timestamp = strtotime($item)) &&
  211.                     ($timestamp > 0) &&
  212.                     ($timestamp < strtotime('+500 years'))) {
  213.             $type = 'DateTime';
  214.             $item = strftime("%Y-%m-%dT%H:%M:%S",$timestamp);
  215.             $style = 'sDT'; // defined in header; tells excel to format date for display
  216.         }
  217.         else {
  218.             $type = 'String';
  219.         }
  220.                
  221.         $item = str_replace('&#039;', '&apos;', htmlspecialchars($item, ENT_QUOTES));
  222.         $output .= "            ";
  223.         $output .= $style ? "<Cell ss:StyleID=\"$style\">" : "<Cell>";
  224.         $output .= sprintf("<Data ss:Type=\"%s\">%s</Data>", $type, $item);
  225.         $output .= "</Cell>\n";
  226.        
  227.         return $output;
  228.     }
  229.    
  230.     function sendHttpHeaders() {
  231.         header("Content-Type: application/vnd.ms-excel; charset=" . $this->encoding);
  232.         header("Content-Disposition: inline; filename=\"" . basename($this->filename) . "\"");
  233.     }
  234.    
  235. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement