Skip to content

Instantly share code, notes, and snippets.

@S1SYPHOS
Created April 5, 2019 13:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save S1SYPHOS/e24eb76b83a1435ddb98e41b685ebfa5 to your computer and use it in GitHub Desktop.
Save S1SYPHOS/e24eb76b83a1435ddb98e41b685ebfa5 to your computer and use it in GitHub Desktop.
<?php
// CSV files > CSV file
function mergeCSV(array $input = [], string $output = '')
{
$count = 0;
foreach (glob($input) as $file) {
if (($handle = fopen($file, 'r')) !== false) {
while (($row = fgetcsv($handle, 0, ';')) !== false) {
$rowCount = count($row);
$array[$count][] = $file;
unset($array[$count][0]);
for ($i = 0; $i < $rowCount; $i++) {
$array[$count][] = $row[$i];
}
$count++;
}
fclose($handle);
}
}
$handle = fopen($output, 'w');
foreach ($array as $fields) {
fputcsv($handle, $fields, ';');
}
fclose($handle);
}
// CSV file > PHP array
function CSV2PHP(string $input, string $delimiter = ';')
{
if (!file_exists($input) || !is_readable($input)) {
return false;
}
$data = [];
$headers =
'foo',
'bar',
'baz',
];
if (($handle = fopen($input, 'r')) !== false) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) {
$row = array_map('utf8_encode', $row);
$data[] = array_combine($headers, $row);
}
fclose($handle);
}
return $data;
}
// PHP array > CSV file
function PHP2CSV(array $data, string $output, string $delimiter = ';')
{
$folder = dirname($output);
if (!is_writable($folder))
return false;
$header = null;
if (($handle = fopen($output, 'w')) !== false) {
foreach ($data as $row) {
if (!$header) {
fputcsv($handle, array_keys($row), $delimiter);
$header = true;
}
fputcsv($handle, $row, $delimiter);
}
fclose($handle);
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment