Skip to content
Browse files

CSV - a dirt-simple class for spitting out CSV documents

  • Loading branch information...
1 parent b36ec24 commit c41ce640a7dc4d0e0f2961996ddba91e3e150075 Brennen Bearnes committed Dec 4, 2012
Showing with 63 additions and 0 deletions.
  1. +63 −0 CSV.php
View
63 CSV.php
@@ -0,0 +1,63 @@
+<?php
+namespace SparkLib;
+
+use \Exception;
+
+/**
+ * CSV - A simple tool to generate a CSV string, ideally
+ * to be sent back to users as text/csv
+ *
+ * This probably exists in thousands of PEAR modules and equally
+ * many other places. But really, it's only a few lines of code.
+ *
+ * This is cheesy and probably fails in common cases, but so far
+ * it has worked well enough for our purposes.
+ */
+class CSV {
+
+ private $_data = array();
+ private $_header = array();
+
+ /**
+ * Add named header fields to the top of the file.
+ */
+ public function addHeader (array $header)
+ {
+ if (! is_array($header))
+ throw new Exception('SparkCSV expects an array as a header');
+
+ $this->_header = $header;
+ }
+
+ /**
+ * Add a row of data.
+ */
+ public function addRow (array $row)
+ {
+ $this->_data[] = $row;
+ }
+
+ /**
+ * Spit out a string containing the entire CSV.
+ */
+ public function render()
+ {
+ $ret = '';
+
+ if(!empty($this->_header)) {
+ foreach($this->_header as $field) {
+ $ret .= '"' . str_replace('"', '""', addslashes($field)) . '",';
+ }
+ $ret[strlen($ret) - 1] = "\n";
+ }
+
+ foreach($this->_data as $row) {
+ foreach($row as $field) {
+ $ret .= '"' . str_replace('"', '""', addslashes($field)) . '",';
+ }
+ $ret[strlen($ret) - 1] = "\n";
+ }
+ return $ret;
+ }
+
+}

0 comments on commit c41ce64

Please sign in to comment.
Something went wrong with that request. Please try again.