Skip to content

Instantly share code, notes, and snippets.

@mrwadson
Last active Sep 21, 2022
Embed
What would you like to do?
CSV read and write
<?php
/*
* Usage
*
require_once __DIR__ . '/CsvFile.php';
$csv = new CsvFile();
$csvData = $csv->getData(__DIR__ . '/path_to_get_csv_file.csv');
...
$csv->saveData(__DIR__ . '/path_to_save_csv_file.csv', $csvData);
*/
class CsvFile
{
private $cols;
public function getData(string $file, int $length = 0, string $separator = ',', string $enclosure = '"'): array
{
if (!file_exists($file)) {
throw new RuntimeException(sprintf('File %s does not exist', $file));
}
$fp = fopen($file, 'r');
$cols = $result = [];
$i = 0;
while ($row = fgetcsv($fp, $length, $separator, $enclosure)) {
if ($i === 0) {
foreach ($row as $col => $name) {
$this->cols[] = $name;
$cols[$col] = strtolower(trim($name));
}
} else {
foreach ($row as $col => $value) {
$result[$i - 1][$cols[$col]] = trim($value);
}
}
$i++;
}
fclose($fp);
return $result;
}
public function saveData(string $file, array $data, bool $columns = true, string $separator = ',', string $enclosure = '"')
{
$fp = fopen($file, 'w');
if ($columns) {
fputcsv($fp, $this->cols, $separator, $enclosure);
}
foreach ($data as $row) {
fputcsv($fp, $row, $separator, $enclosure);
}
fclose($fp);
}
public function getDataMapping(string $file, int $asKey, array $asValue): array
{
$result = [];
$csvData = $this->getData($file);
$keyName = $this->getKeyByIndex(reset($csvData), $asKey);
foreach ($csvData as $item) {
if (isset($item[$keyName])) {
$values = [];
foreach ($asValue as $val) {
$keyNameInValue = $this->getKeyByIndex(reset($csvData), $val);
if (isset($item[$keyNameInValue])) {
$values[] = $item[$keyNameInValue];
}
}
$result[$item[$keyName]] = count($values) > 1 ? $values : reset($values);
}
}
return $result;
}
private function getKeyByIndex(array $row, int $key): string
{
$keys = array_keys($row);
if (isset($keys[$key])) {
return $keys[$key];
}
throw new OutOfRangeException(sprintf('Out on range key #%d in array', $key));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment