A modest collection of PHP libraries used at SparkFun.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.3 KiB

  1. <?php
  2. namespace SparkLib;
  3. use \Exception;
  4. /**
  5. * CSV - A simple tool to generate a CSV string, ideally
  6. * to be sent back to users as text/csv
  7. *
  8. * This probably exists in thousands of PEAR modules and equally
  9. * many other places. But really, it's only a few lines of code.
  10. *
  11. * This is cheesy and probably fails in common cases, but so far
  12. * it has worked well enough for our purposes.
  13. */
  14. class CSV {
  15. private $_data = array();
  16. private $_header = array();
  17. /**
  18. * Add named header fields to the top of the file.
  19. */
  20. public function addHeader (array $header)
  21. {
  22. if (! is_array($header))
  23. throw new Exception('SparkLib\CSV expects an array as a header');
  24. $this->_header = $header;
  25. }
  26. /**
  27. * Add a row of data.
  28. */
  29. public function addRow (array $row)
  30. {
  31. $this->_data[] = $row;
  32. }
  33. /**
  34. * Spit out a string containing the entire CSV.
  35. */
  36. public function render()
  37. {
  38. $ret = '';
  39. if(!empty($this->_header)) {
  40. foreach($this->_header as $field) {
  41. $ret .= '"' . str_replace('"', '""', addslashes($field)) . '",';
  42. }
  43. $ret[strlen($ret) - 1] = "\n";
  44. }
  45. foreach($this->_data as $row) {
  46. foreach($row as $field) {
  47. $ret .= '"' . str_replace('"', '""', addslashes($field)) . '",';
  48. }
  49. $ret[strlen($ret) - 1] = "\n";
  50. }
  51. return $ret;
  52. }
  53. }