CsvReader.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. }