Add to Favorites

CSV paginated display

There are times when you just want to simply output a csv format to the web purely for informational purposes. You don't want to provide a download but instead just show a paginated view of the csv file. I have written a script that can do just that. This script takes your csv file and then writes php code that breaks up the data into multiple pages, it stores all the data and basic scripting into one portable php file.

The script takes a csv upload file, then converts rows into html table rows. It creates multiple html tables serialized out into a php array that is used with a simple script to display by page number.

 
<?php
    
    if ( ! empty($_FILES['file']['name']) ) {
        $f = fopen($_FILES['file']['tmp_name'],'r');
        
        $head = fgetcsv($f,0,',','"');
        $num_per_page = 50;
        
        $out = array(1 => '<table width="100%" cellspacing="0" cellpadding="1"><tr><th>'. join('</th><th>',$head) .'</th></tr>');
        $k = count($out);
        
        $i = 0;
        $p = 1;
        $z = -1;
        while( $arr = fgetcsv($f,0,',','"') ) {
            $arr = array_pad($arr,$k,'');
            if ( $i >= $num_per_page ) {
                $i = 0;
                $out[$p] = $out[$p] .'</table>';
                $out[$p] = $out[$p] .'<div style="text-align: right;">';
                if ( $p > 1 ) {
                    $out[$p] = $out[$p] .'<a href="?p='. ($p -1 ) .'">&lt; Previous</a> &nbsp;&nbsp;&nbsp;';
                }
                $out[$p] = $out[$p] .'<a href="?p='. ($p +1 ) .'">Next &gt;</a>';
                $out[$p] = $out[$p] .'</div>';
                
                $p++;
                $out[$p] = '<table width="100%" cellspacing="0" cellpadding="1"><tr><th>'. join('</th><th>',$head) .'</th></tr>';
            }
            $z *= -1;
            $out[$p] = $out[$p] .'<tr '. ( $z > 0 ? 'class="odd"' : '' ) .'><td>'. join('</td><td>',$arr) .'</td></tr>';
            $i++;
        }
        if ( $i > 0 ) {
            $out[$p] = $out[$p] .'</table>';
        }
        if ( $p > 1 ) {
            $out[$p] = $out[$p] .'<div style="text-align: right;">';
            $out[$p] = $out[$p] .'<a href="?p='. ($p -1 ) .'">&lt; Previous</a> &nbsp;&nbsp;&nbsp;';
            $out[$p] = $out[$p] .'</div>';
        }
        
        echo '<pre>'. htmlspecialchars('<?php' ."\n"
            .'$arr = '. var_export($out,true) .'; $p = 1; if ( ! empty($_GET[\'p\']) ) $p = intval($_GET[\'p\']); if ( ! array_key_exists($p,$arr) ) $p = 1; echo $arr[$p];'
            . "\n". '?>'
        );
        
    } else {
?>
    <form method="post" enctype="multipart/form-data">
        CSV File<input type="file" name="file" /> <input type="submit" value="Submit" />
    </form>
<?php
    }
    
?>
 

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up