CSV file to table

My second module :slight_smile:

It converts the csv file first to a array and the array is converted to a table.

Cheers, Maarten

<section class="column"> 
<?php function csv_to_array($filename='', $delimiter=';')
{
	if(!file_exists($filename) || !is_readable($filename))
		return FALSE;
	
	$header = NULL;
	$data = array();
	if (($handle = fopen($filename, 'r')) !== FALSE)
	{
		while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
		{
			if(!$header)
				$header = $row;
			else
				$data[] = array_combine($header, $row);
		}
		fclose($handle);
	}
	return $data;
}


?> 
<?php function array_to_table($array, $table = true)
{
    $out = '';
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if (!isset($tableHeader)) {
                $tableHeader =
                    '<th>' .
                    implode('</th><th>', array_keys($value)) .
                    '</th>';
            }
            array_keys($value);
            $out .= '<tr>';
            $out .= array_to_table($value, false);
            $out .= '</tr>';
        } else {
            $out .= "<td>$value</td>";
        }
    }

    if ($table) {
        return '<table class="highlight">' . $tableHeader . $out . '</table>';
    } else {
        return $out;
    }
}
    
 ?>
<?php $csvfile = $module->files()->filterBy('extension', 'csv')->filterBy('filename', '*=', $site->language()->code())->last(); ?>   

<?php if ($csvfile) : ?>     
<?php $tablearray = (csv_to_array($csvfile)); ?>
<?php echo (array_to_table($tablearray, true)); ?>
 <?php else: ?> 
<h4>No results</h4>
 <?php endif; ?>    
      
</section> 

how about using basic php fgetcsv and array_map instead of the for loop?

using kirby toolkit file api could also improve readability of code.

edited: nevermind. fgetcsv needs a handle.