csv_writer.class.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Write array data to a stream in CSV format. Usage:
  4. *
  5. * $writer = CsvWriter::create('path');
  6. *
  7. * $writer->put($headers);
  8. * $writer->put($line_1);
  9. * $writer->put($line_2);
  10. *
  11. * @copyright (c) 2012 University of Geneva
  12. * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
  13. * @author Laurent Opprecht <laurent@opprecht.info>
  14. */
  15. class CsvWriter
  16. {
  17. /**
  18. *
  19. * @param string|object $stream
  20. * @return CsvWriter
  21. */
  22. static function create($stream, $delimiter = ';', $enclosure = '"')
  23. {
  24. return new self($stream, $delimiter, $enclosure);
  25. }
  26. protected $stream = null;
  27. protected $delimiter = '';
  28. protected $enclosure = '';
  29. function __construct($stream, $delimiter = ';', $enclosure = '"')
  30. {
  31. $this->stream = $stream;
  32. $this->delimiter = $delimiter ? substr($delimiter, 0, 1) : ';';;
  33. $this->enclosure = $enclosure ? substr($enclosure, 0, 1) : '"';;
  34. }
  35. function get_delimiter()
  36. {
  37. return $this->delimiter;
  38. }
  39. function get_enclosure()
  40. {
  41. return $this->enclosure;
  42. }
  43. function get_stream(){
  44. return $this->stream;
  45. }
  46. /**
  47. *
  48. * @return FileWriter
  49. */
  50. protected function stream()
  51. {
  52. if (is_string($this->stream)) {
  53. $this->stream = new FileWriter($this->stream);
  54. }
  55. return $this->stream;
  56. }
  57. function write($items)
  58. {
  59. $items = is_array($items) ? $items : func_get_args();
  60. $this->put($items);
  61. }
  62. function writeln($items)
  63. {
  64. $items = is_array($items) ? $items : func_get_args();
  65. $this->put($items);
  66. }
  67. function put($items)
  68. {
  69. $items = is_array($items) ? $items : func_get_args();
  70. $enclosure = $this->enclosure;
  71. $fields = array();
  72. foreach ($items as $item) {
  73. $fields[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $item) . $enclosure;
  74. }
  75. $delimiter = $this->delimiter;
  76. $line = implode($delimiter, $fields);
  77. $this->stream()->writeln($line);
  78. }
  79. function close()
  80. {
  81. if (is_object($this->stream)) {
  82. $this->stream->close();
  83. }
  84. $this->stream = null;
  85. }
  86. }