108 lines
2.9 KiB
PHP
108 lines
2.9 KiB
PHP
<?php
|
|
function convert_csv($inputFile, $outputFile) {
|
|
$strip_bom = function ($s) {
|
|
if ($s === null) return '';
|
|
if (strncmp($s, "\xEF\xBB\xBF", 3) === 0) {
|
|
return substr($s, 3);
|
|
}
|
|
return $s;
|
|
};
|
|
|
|
$in = @fopen($inputFile, 'r');
|
|
if ($in === false) {
|
|
return false;
|
|
}
|
|
|
|
// Read header
|
|
$header = fgetcsv($in, 0, ',', '"', '\\');
|
|
if ($header === false) {
|
|
fclose($in);
|
|
return false;
|
|
}
|
|
|
|
// Normalize header names and build index map
|
|
$index = [];
|
|
foreach ($header as $i => $name) {
|
|
$name = trim($strip_bom($name));
|
|
$index[$name] = $i;
|
|
}
|
|
|
|
$get = function ($row, $name) use ($index) {
|
|
if (!isset($index[$name])) return '';
|
|
$i = $index[$name];
|
|
return isset($row[$i]) ? trim($row[$i]) : '';
|
|
};
|
|
|
|
$out = @fopen($outputFile, 'w');
|
|
if ($out === false) {
|
|
fclose($in);
|
|
return false;
|
|
}
|
|
|
|
// Output header using semicolon separator
|
|
$outHeader = [
|
|
'Data księgowania',
|
|
'Nadawca / Odbiorca',
|
|
'Adres nadawcy / odbiorcy',
|
|
'Rachunek źródłowy',
|
|
'Rachunek docelowy',
|
|
'Tytuł',
|
|
'Kwota'
|
|
];
|
|
fputcsv($out, $outHeader, ';');
|
|
|
|
while (($row = fgetcsv($in, 0, ',', '"', '\\')) !== false) {
|
|
// Skip completely empty rows
|
|
$nonEmpty = false;
|
|
foreach ($row as $v) {
|
|
if ($v !== null && $v !== '') { $nonEmpty = true; break; }
|
|
}
|
|
if (!$nonEmpty) continue;
|
|
|
|
$date = $get($row, 'Date completed (UTC)');
|
|
if ($date === '') {
|
|
$date = $get($row, 'Date started (UTC)');
|
|
}
|
|
|
|
$description = $get($row, 'Description');
|
|
$payer = $get($row, 'Payer');
|
|
$counterparty = $description !== '' ? $description : $payer;
|
|
|
|
$sourceAccount = $get($row, 'Account');
|
|
|
|
$benefIban = $get($row, 'Beneficiary IBAN');
|
|
$benefAccNo = $get($row, 'Beneficiary account number');
|
|
$destAccount = $benefIban !== '' ? $benefIban : $benefAccNo;
|
|
|
|
$reference = $get($row, 'Reference');
|
|
$type = $get($row, 'Type');
|
|
$title = $reference !== '' ? $reference : str_replace('_', ' ', $type);
|
|
if ($title === '' && $counterparty !== '') {
|
|
$title = $counterparty;
|
|
}
|
|
|
|
// Prefer Amount, then Total amount, then Orig amount
|
|
$amount = $get($row, 'Amount');
|
|
if ($amount === '') $amount = $get($row, 'Total amount');
|
|
if ($amount === '') $amount = $get($row, 'Orig amount');
|
|
|
|
// Normalize decimal separator just in case
|
|
$amount = str_replace(',', '.', $amount);
|
|
|
|
$outputRow = [
|
|
$date,
|
|
$counterparty,
|
|
'',
|
|
$sourceAccount,
|
|
$destAccount,
|
|
$title,
|
|
$amount
|
|
];
|
|
|
|
fputcsv($out, $outputRow, ';');
|
|
}
|
|
|
|
fclose($in);
|
|
fclose($out);
|
|
return true;
|
|
} |