CSVReader.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * CSVReader class to read CSV files from a specified directory.
  4. * It reads all CSV files, combines their headers, and returns an array of rows.
  5. */
  6. class CSVReader {
  7. /**
  8. * Directory where CSV files are stored.
  9. * @var string
  10. */
  11. private $dir;
  12. /**
  13. * Constructor to initialize the CSVReader with a directory.
  14. *
  15. * @param string $directory The directory containing CSV files.
  16. */
  17. public function __construct($directory) {
  18. $this->dir = rtrim($directory, '/') . '/';
  19. }
  20. /**
  21. * Reads all CSV files in the specified directory and returns an array of rows.
  22. *
  23. * @return array An array of associative arrays representing the rows in the CSV files.
  24. */
  25. public function readAll() {
  26. $rows = array();
  27. foreach (glob($this->dir . '*.csv') as $file) {
  28. if (($h = fopen($file, 'r')) !== false) {
  29. $header = fgetcsv($h, 0, ',', '"', '');
  30. while (($data = fgetcsv($h, 0, ',', '"', '')) !== false) {
  31. $rows[] = array_combine($header, $data);
  32. }
  33. fclose($h);
  34. }
  35. }
  36. return $rows;
  37. }
  38. /**
  39. * Converts an array of CSV rows into a string format.
  40. *
  41. * @param array $csvRows An array of associative arrays representing the CSV rows.
  42. * @return string A string representation of the CSV rows.
  43. */
  44. public function toString($csvRows) {
  45. $csvString = '';
  46. foreach ($csvRows as $csvRow) {
  47. $csvString .= "- " . implode(" | ", $csvRow) . "\n";
  48. }
  49. return $csvString;
  50. }
  51. }