Skip to content

Instantly share code, notes, and snippets.

@fridolin-koch
Last active December 26, 2015 10:09
Show Gist options
  • Save fridolin-koch/7134666 to your computer and use it in GitHub Desktop.
Save fridolin-koch/7134666 to your computer and use it in GitHub Desktop.
CSV to Redmine table
#!/usr/bin/env php
<?php
if ($argc < 2) {
printf('Usage: %s <filename>' . PHP_EOL, $argv[0]);
exit(1);
}
if (!file_exists($argv[1])) {
printf('File %s was not found' . PHP_EOL, $argv[1]);
exit(1);
}
function maxStrlen(array $string)
{
$length = 0;
foreach ($string as $str) {
if (strlen($str) > $length) {
$length = strlen($str);
}
}
return $length;
}
$cols = [];
$lines = file($argv[1]);
foreach ($lines as $line) {
$row = str_getcsv(utf8_encode($line), ';', '');
foreach ($row as $colIndex => $cell) {
if ($cell != '') {
if (!array_key_exists($colIndex, $cols)) {
$cols[$colIndex] = [];
}
$cols[$colIndex][] = trim($cell);
}
}
}
foreach ($cols as $colIndex => $col) {
$maxLen = maxStrlen($col);
foreach ($col as $cellIndex =>$cell) {
$col[$cellIndex] = str_pad($cell, $maxLen);
}
$cols[$colIndex] = $col;
}
$table = '';
for ($j = 0; $j < count($cols[0]); $j++) {
$table .= '|';
for ($i = 0; $i < count($cols); $i++) {
$table .= $cols[$i][$j] . ' | ';
}
$table .= PHP_EOL;
}
echo $table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment