auditionadmin/app/Services/CsvImportService.php

43 lines
1.1 KiB
PHP

<?php
namespace App\Services;
class CsvImportService
{
/**
* Read a CSV file and return its contents as an array
*
* @param string $filePath Full path to the CSV file
* @param bool $trimHeaders Whether to trim whitespace from header names
* @return array Array of rows with header keys
*/
public function readCsv(string $filePath, bool $trimHeaders = true): array
{
if (! file_exists($filePath)) {
throw new \RuntimeException("File not found: {$filePath}");
}
$handle = fopen($filePath, 'r');
if ($handle === false) {
throw new \RuntimeException("Unable to open file: {$filePath}");
}
$header = null;
$rows = [];
while (($line = fgetcsv($handle, 0, ',')) !== false) {
if (! $header) {
$header = $trimHeaders ? array_map('trim', $line) : $line;
continue;
}
$row = array_combine($header, $line);
$rows[] = $row;
}
fclose($handle);
return $rows;
}
}