Posted By

TimoZachi on 08/21/12


Tagged

class generator download csv manipulatior


Versions (?)

CSV handler class


 / Published in: PHP
 

Class that convert arrays to csv format, downloads CSV files and saves to disk on server.

  1. <?php
  2. class CSVData
  3. {
  4. public $colDelimiter = ';';
  5.  
  6. public function __construct($colDelimiter = ';')
  7. {
  8. $this->colDelimiter = $colDelimiter;
  9. }
  10. /**
  11. * Converts an array of data to CSV format.
  12. *
  13. * @param string $head The CSV header. Example: array('User id', 'User Name', 'User Email');
  14. * @param string $data The CSV data. Example:
  15. * array(
  16. * array(1, 'John', '[email protected]' ),
  17. * array(2, 'Andrew', '[email protected]'),
  18. * array(3, 'Ana', '[email protected]' )
  19. * );
  20. * @return string The Proper formatted CSV string
  21. */
  22. public function arrayToCSV($head, $data)
  23. {
  24. $csv = '';
  25. array_unshift($data, $head);
  26. foreach($data as $d) $csv .= implode($this->colDelimiter, array_map(array($this, '_quoteStr'), $d)) . "\n";
  27. return $csv;
  28. }
  29. /**
  30. * Downloads CSV string to client as a file
  31. * @param string $csv A properly formatted CSV string
  32. * @param string $fileName Name of the file to be downloaded. Example: 'mycsv'
  33. * @param bool $noCache [Optional] If true, headers will be sent to prevent
  34. * browser caching of the CSV.
  35. */
  36. public function downloadCSV($csv, $fileName, $noCache = false)
  37. {
  38. $len = strlen($csv);
  39.  
  40. if($noCache) $this->_noCacheHeaders();
  41. header("Content-Type: text/csv");
  42. header("Content-Disposition: attachment; filename=\"{$fileName}.csv\";");
  43. header('Content-Transfer-Encoding: binary');
  44. header("Content-Length: {$len}");
  45. echo $csv;
  46. }
  47. /**
  48. * Saves a CSV string as a CSV file in the server
  49. * @param string $csv A properly formatted CSV string
  50. * @param string $path Where to save the file. Example: archives/csv/.
  51. * Notice the / at the end of the path.
  52. * @param string $fileName Name of the file to be saved. Example: 'mycsv'
  53. */
  54. public function saveCSV($csv, $path, $fileName)
  55. {
  56. $handle = fopen($path . $fileName . '.csv', 'w');
  57. if($handle === false) throw new Exception(
  58. 'Could not create file: ' . $path . $fileName . '.csv'
  59. );
  60. fwrite($handle, $csv);
  61. fclose($handle);
  62. }
  63. //////////////////////////////////////////////////////////////////////////////////////////
  64. //PRIVATES
  65. //////////////////////////////////////////////////////////////////////////////////////////
  66. /** Quotes CSV column if necessary. */
  67. private function _quoteStr($str)
  68. {
  69. if(strpos($str, '"') !== false || strpos($str, $this->colDelimiter) !== false)
  70. {
  71. $str = '"' . str_replace('"', '""', $str) . '"';
  72. }
  73. return $str;
  74. }
  75. /** Sends no caching headers to browser. */
  76. private function _noCacheHeaders()
  77. {
  78. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); //Date in the past
  79. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); //Now
  80. header('Cache-Control: no-store, no-cache, must-revalidate');
  81. header('Cache-Control: post-check=0, pre-check=0', false);
  82. header('Pragma: no-cache');
  83. }
  84. }
  85.  
  86. //Usage of class
  87. $head = array('User id', 'User Name', 'User Email'); //The head will probably be static
  88. $data = array( //This data could be grabbed from a database
  89. array(1, 'John', '[email protected]' ),
  90. array(2, 'Andrew', '[email protected]' ),
  91. array(3, 'Ana', '[email protected]' ),
  92. array(4, 'Carlos', '[email protected]' ),
  93. array(5, 'Christina', '[email protected]'),
  94. array(6, 'Zed', '[email protected]' ),
  95. array(7, 'Nina', '[email protected]' ),
  96. array(8, 'Gabriela', '[email protected]' ),
  97. array(9, 'Joseph', '[email protected]' ),
  98. array(10, 'Ariel', '[email protected]' )
  99. );
  100.  
  101. $csv = new CSVData(); //Create a new instance
  102. //Transform the array to CSV string
  103. $csvStr = $csv->arrayToCSV($head, $data);
  104. //Download CSV, the browser will prompt
  105. //the user to download the file
  106. $csv->downloadCSV($csvStr, 'users', true);
  107. //Whrite csv data to the server
  108. $csv->saveCSV($csvStr, 'archives/csv/', 'users');
  109. ?>

Report this snippet  

You need to login to post a comment.