| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?php
- /**
- * CSVReader class to read CSV files from a specified directory.
- * It reads all CSV files, combines their headers, and returns an array of rows.
- */
- class CSVReader {
- /**
- * Directory where CSV files are stored.
- * @var string
- */
- private $dir;
- /**
- * Constructor to initialize the CSVReader with a directory.
- *
- * @param string $directory The directory containing CSV files.
- */
- public function __construct($directory) {
- $this->dir = rtrim($directory, '/') . '/';
- }
- /**
- * Reads all CSV files in the specified directory and returns an array of rows.
- *
- * @return array An array of associative arrays representing the rows in the CSV files.
- */
- public function readAll() {
- $rows = array();
- foreach (glob($this->dir . '*.csv') as $file) {
- if (($h = fopen($file, 'r')) !== false) {
- $header = fgetcsv($h, 0, ',', '"', '');
- while (($data = fgetcsv($h, 0, ',', '"', '')) !== false) {
- $rows[] = array_combine($header, $data);
- }
- fclose($h);
- }
- }
- return $rows;
- }
- /**
- * Converts an array of CSV rows into a string format.
- *
- * @param array $csvRows An array of associative arrays representing the CSV rows.
- * @return string A string representation of the CSV rows.
- */
- public function toString($csvRows) {
- $csvString = '';
- foreach ($csvRows as $csvRow) {
- $csvString .= "- " . implode(" | ", $csvRow) . "\n";
- }
- return $csvString;
- }
- }
|