Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * CSV helper for cakePHP.
- *
- * PHP version 5
- *
- * Licensed under The MIT License
- *
- * @copyright Adam Royle
- * @license http://www.opensource.org/licenses/mit-license.php The MIT License
- * @link http://bakery.cakephp.org/articles/view/csv-helper-php5
- */
- class CsvHelper extends AppHelper
- {
- public $delimiter = ',';
- public $enclosure = '"';
- public $clean_output = true;
- /* This option preserves leading zeros on numeric data when opened in Excel.
- * Use it ONLY when the csv file is going to be opened in Excel, as it uses
- * non-standard syntax, and will probably break in other systems.
- */
- public $preserveLeadingZerosInExcel = false;
- private $line = array();
- private $buffer;
- private $filename = 'export.csv';
- private $trans_tbl = null;
- public function CsvHelper()
- {
- $this->clear();
- }
- /**
- * Clears internal buffer. This is called automatically by CsvHelper::render()
- *
- * @access public
- */
- public function clear()
- {
- $this->line = array();
- $this->buffer = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
- }
- /**
- * Adds a single field value to the buffer. You must call $csv->endRow() to commit fields to the buffer.
- *
- * @param string $value Field value
- * @access public
- */
- public function addField($value)
- {
- $this->line[] = ($this->clean_output ? $this->cleanStr($value) : $value);
- }
- /**
- * Commits the row of fields that were added by addField()
- *
- * @access public
- */
- public function endRow()
- {
- $this->addRow($this->line);
- $this->line = array();
- }
- /**
- * Adds a single row to the buffer.
- *
- * @param array $row Data to be added
- * @access public
- */
- public function addRow($row)
- {
- if ($this->clean_output)
- {
- $row = $this->cleanStr($row);
- }
- if ($this->preserveLeadingZerosInExcel)
- {
- /* convert the number to a string formula
- */
- foreach ($row as $key => $value)
- {
- if (strlen($value) > 1 && $value[0] == '0' && is_numeric($value))
- {
- $row[$key] = '="'.$value.'"';
- }
- }
- }
- fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
- }
- /**
- * Adds a multi-dimensional array to the buffer.
- *
- * @param array $data Multi-dimensional array
- * @param boolean $addFieldNames Add a row of field names before adding data
- * @access public
- */
- function addGrid($data, $addFieldNames = true, $fieldList = null)
- {
- if (!$data)
- {
- return false;
- }
- if (@is_array(reset($row = reset($data))))
- {
- /* Array generated by cakePHP model
- * eg.
- * $data = array(
- * array(
- * 'Model' => array('field_name' => 'field value')
- * ),
- * array(
- * 'Model' => array('field_name' => 'field value')
- * )
- * )
- */
- $defaultModel = key($row);
- if ($this->filename === null)
- {
- $this->setFilename(Inflector::pluralize($defaultModel));
- }
- if ($fieldList)
- {
- $fields = array();
- foreach ($fieldList as $fieldName)
- {
- if (strpos($fieldName, '.'))
- {
- list($modelName, $fieldName) = explode('.', $fieldName);
- }
- else
- {
- $modelName = $defaultModel;
- }
- $fields[] = array(Inflector::humanize($modelName), $fieldName);
- }
- if ($addFieldNames)
- {
- foreach ($fields as $field)
- {
- if ($field[0] != $defaultModel)
- {
- $this->addField($field[0].' '.Inflector::humanize($field[1]));
- }
- else
- {
- $this->addField(Inflector::humanize($field[1]));
- }
- }
- $this->endRow();
- }
- foreach ($data as $row)
- {
- foreach ($fields as $field)
- {
- @$this->addField($row[$field[0]][$field[1]]);
- }
- $this->endRow();
- }
- }
- else
- {
- if ($addFieldNames)
- {
- foreach (reset($row) as $key => $value)
- {
- $this->addField(Inflector::humanize($key));
- }
- $this->endRow();
- }
- foreach ($data as $row)
- {
- $this->addRow($row[$defaultModel]);
- }
- }
- }
- else
- {
- /* Regular 2-dimensional array (with or without keys).
- * eg.
- * $data = array(
- * array('field_name' => 'field_value'),
- * array('field_name' => 'field_value')
- * )
- * or
- * $data = array(array('field value'), array('field value'))
- */
- if ($fieldList)
- {
- if ($addFieldNames)
- {
- foreach ($fieldList as $fieldName)
- {
- $this->addField(Inflector::humanize($fieldName));
- }
- $this->endRow();
- }
- foreach ($data as $row)
- {
- foreach ($fieldList as $fieldName)
- {
- @$this->addField($row[$fieldName]);
- }
- $this->endRow();
- }
- }
- else
- {
- if ($addFieldNames)
- {
- foreach (reset($data) as $key => $value)
- {
- $this->addField(Inflector::humanize($key));
- }
- $this->endRow();
- }
- foreach ($data as $row)
- {
- $this->addRow($row);
- }
- }
- }
- }
- /**
- * Clean strings up a bit before sending them to output
- *
- * @param mixed string or array of data
- * @return mixed string or array of cleaned data
- * @access private
- */
- private function cleanStr($data)
- {
- $flatten = false;
- if (!is_array($data))
- {
- $flatten = true;
- $data = array($data);
- }
- foreach ($data as $key => $datum)
- {
- if (is_string($datum))
- {
- $datum = str_replace(array("\r", "\n", "\t"), ' ', trim($datum));
- if (!empty($datum))
- {
- $data[$key] = strtr($datum, $this->getTransTable());
- }
- }
- }
- return ($flatten ? $data[0] : $data);
- }
- /**
- * Get the translation table used for entitites and special chars
- *
- * @param void
- * @return mixed the translation table array
- * @access private
- */
- private function getTransTable()
- {
- if (!is_null($this->trans_tbl)) return $this->trans_tbl;
- $ttr = get_html_translation_table(HTML_ENTITIES);
- foreach($ttr as $k => $v)
- {
- $this->trans_tbl[$v] = utf8_encode($k);
- }
- return $this->trans_tbl;
- }
- /**
- * Outputs headers
- *
- * @param string $filename Filename to save as
- * @access public
- */
- public function renderHeaders($filename = null)
- {
- if (is_string($filename) && !empty($filename))
- {
- $this->setFilename($filename);
- }
- header ('Expires: Mon, 1 Apr 1974 05:00:00 GMT');
- header ('Last-Modified: ' . gmdate('D,d M YH:i:s') . ' GMT');
- header ('Pragma: no-cache');
- header('Content-disposition:attachment;filename='.$this->filename);
- //header('Content-type:application/vnd.ms-excel');
- //header('Content-type: application/vnd.ms-excel; charset=UTF-16LE');
- header('Content-Type: application/csv');
- }
- /**
- * Sets the output filename. Automatically appends .csv if necessary.
- *
- * @param string $filename Filename to save as
- * @access public
- */
- public function setFilename($filename)
- {
- if (!empty($filename))
- {
- if (strtolower(substr($filename, -4)) != '.csv')
- {
- $filename .= '.csv';
- }
- $this->filename = $filename;
- }
- }
- /**
- * Returns CSV string and clears internal buffer. Outputs headers() if necessary.
- *
- * @param mixed $outputHeaders Boolean to determine if should output headers, or a string to set the filename
- * @param string $to_encoding Encoding to use
- * @param string $from_encoding
- * @return string String CSV formatted string
- * @access public
- */
- public function render($outputHeaders = true, $to_encoding = null, $from_encoding = 'auto')
- {
- if ($outputHeaders)
- {
- if (is_string($outputHeaders))
- {
- $this->setFilename($outputHeaders);
- }
- $this->renderHeaders();
- }
- rewind($this->buffer);
- $output = stream_get_contents($this->buffer);
- if ($to_encoding)
- {
- $output = mb_convert_encoding($output, $to_encoding, $from_encoding);
- }
- else
- {
- //$output = chr(255).chr(254).mb_convert_encoding($output, 'UTF-16LE', 'UTF-8');
- }
- return $this->output($output);
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement