CSV Reader in PHP
This CSV reader script I am pretty proud of. Its functional and outputs the csv as an organized grid with ascii separators.
$ csvreader.php example.csv
+------------+-----------+-------------+--------+---------------+---------------+-----------+-----------+-------------+
| First Name | Last Name | Nationality | Gender | Date of Birth | Time of Birth | Date/Time | PHP Coder | Sanity %Age |
+------------+-----------+-------------+--------+---------------+---------------+-----------+-----------+-------------+
| Mark | Baker | British | M | 19-Dec-1960 | 01:30 | =E2+F2 | TRUE | 32% |
+------------+-----------+-------------+--------+---------------+---------------+-----------+-----------+-------------+
| Toni | Baker | British | F | 24-Nov-1950 | 20:00 | =E3+F3 | FALSE | 95% |
+------------+-----------+-------------+--------+---------------+---------------+-----------+-----------+-------------+
| Rachel | Baker | British | F | 7-Dec-1982 | 00:15 | =E4+F4 | FALSE | 100% |
+------------+-----------+-------------+--------+---------------+---------------+-----------+-----------+-------------+
The Code
#!/usr/bin/php
<?php
try
{
$file = $argv[1];
if(!$file || !is_file($file))
{
throw new Exception('No file '.$file);
}
if(!is_readable($file))
{
throw new Exception('Not readable '.$file);
}
}
catch(Exception $e)
{
echo "ERROR: ".$e->getMessage()."\n";
exit(1);
}
# get the CSV into an array
$totalWidth = 0;
$numColumns = 0;
$widths = array();
$lines = array();
$file = fopen($file, 'r');
$i = 0;
while (($line = fgetcsv($file)) !== FALSE)
{
$lines[] = $line;
foreach($line as $k => $field)
{
if($i == 0)
$numColumns++;
$len = strlen($field);
if(!isset($widths[$k]))
{
$widths[$k] = $len;
}
elseif($widths[$k] < $len)
{
$widths[$k] = $len;
}
}
$i++;
}
fclose($file);
# printer formats
$lpad = 1;
$rpad = 1;
$divider = "|";
$totalWidth = array_sum($widths);
$lineLength = $totalWidth + ($numColumns * $lpad) + ($numColumns * $rpad) + ($numColumns * strlen($divider)) + strlen($divider);
# meta data
#echo "number of rows = $i\n";
#echo "number of columns = $numColumns\n";
# top row
echo '+';
foreach($widths as $width)
{
echo str_repeat("-", $width + $lpad + $rpad) . '+';
}
echo "\n";
# rows
#echo str_repeat("-", $lineLength)."\n";
foreach($lines as $line)
{
# data
echo $divider;
foreach($line as $k => $field)
{
$colwidth = $widths[$k];
echo str_repeat(' ', $lpad) . str_pad($field, $colwidth + $rpad) . $divider;
}
# divider row
echo "\n+";
foreach($widths as $width)
{
echo str_repeat("-", $width + $lpad + $rpad) . '+';
}
echo "\n";
#echo "\n".str_repeat("-", $lineLength)."\n";
}