I’m not sure how to ask this question properly. I modify CSV files in more steps in PHP. I’ve created a class for the files, and some methods. In most methods I have to read the CSV and change something in the while() loop. So now I have severeal methods, that use almost the same code, there are only differences inside the while() loops and I was thinking, this should be possible to encapsulate into a baseMethod() but unfortunately I’m having no luck so far. I was trying something like this:
class Csv {
public $src;
public $trgt;
public $sortCols = [];
public function __construct($sortCols = [], etc...) {
$this->sortCols = $sortCols;
etc.
}
function baseMethod(callable $callback) {
$rownum = 0;
$header = [];
if (($fhs = fopen($this->src, 'r+')) &&
($fht = fopen($this->trgt, 'w+'))) {
while (($csvr = fgetcsv($fhs, null, ';', '"')) !== false) {
if ($rownum++ == 1) {
$header = $csvr;
fputcsv($fht, $header);
} else {
$row = array_combine($header, $csvr);
$row = $callback($row, $header); # only this part changes, and sometimes the header...
fputcsv($fht, $row);
}
}
fclose($fhs);
fclose($fht);
}
}
function sortColums() {
$this->baseMethod(function($row, $header) {
foreach ($this->sortCols as $col) {
if (!empty($row[$col]) && str_contains($row[$col], '|')) {
$colValues = explode('|', $row[$col]);
sort($colValues);
$row[$col] = implode('|', $colValues);
}
}
return $row;
});
}
}
but the target file written was much smaller and contains only commas besides the header, and honestly I have no clue why. UPDATE: If I put the foreach of the callback (anonymous) function directly into the baseMethod() inside the while() loop, it is working properly. Is it possible anyway what I’m trying to do? Can you please point me to the right direction?
4
class Csv {
public $src;
public $trgt;
private $delimiter = ';';
private $enclosure = '"';
function baseMethod(callable $callback) {
$rownum = 0;
$header = [];
if (($fhs = fopen($this->src, 'r')) &&
($fht = fopen($this->trgt, 'w'))) {
while (($csvr = fgetcsv($fhs, null, $this->delimiter, $this->enclosure)) !== false) {
if ($rownum == 0) {
$header = $csvr;
fputcsv($fht, $header, $this->delimiter, $this->enclosure);
} else {
$row = array_combine($header, $csvr);
$row = $callback($row, $header);
fputcsv($fht, $row, $this->delimiter, $this->enclosure);
}
$rownum++;
}
fclose($fhs);
fclose($fht);
}
}
function sortColumns() {
$this->baseMethod(function($row, $header) {
foreach ($this->sortCols as $col) {
if (!empty($row[$col]) && str_contains($row[$col], '|')) {
$colValues = explode('|', $row[$col]);
sort($colValues);
$row[$col] = implode('|', $colValues);
}
}
return $row;
});
}
}
Aras Bulak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2