Parse CSV

Reads a CSV, either local or remote, and outputs in HTML table and/or total of selected column.

Usage:
$jlv_csv->printTable();
$jlv_csv->printColumnTotal(2);

jlv-read-csv.php

<?php
/*
Plugin Name: CSV Parser 
Plugin URI: https://abuyasmeen.com/parse-csv/
Description: Loads a CSV file and ouputs either a column total or a formatted html table.
Version: 0.1
Author: Jeremy Varnham
Author URI: https://abuyasmeen.com
License: GPL2
*/

define('JLV_PLUGIN_PATH', WP_PLUGIN_DIR.'/'. dirname( plugin_basename( __FILE__ ) ));
require_once( JLV_PLUGIN_PATH . '/php/jlv-csv-functions.php' );

$jlv_csv = new CSVParser;

/**
* Set input
*/
$jlv_csv->setInputFile('https://dl.dropboxusercontent.com/u/3542031/Attendance_Data.csv');
$jlv_csv->setOutputStyle('bootstrap.min');

/**
* Do output
*/
// $jlv_csv->printTable();
// echo '<br><b>Total Attendees: </b> ';
// $jlv_csv->printColumnTotal(2);

?>

jlv-csv-functions.php

<?php

/**
*
* Loads a CSV file and ouputs either a column total or a formatted html table.
*
*/

## =================== INITIATE =================== ##

## 1. Make new instance:

		// $sap_stats = new CSVParser;

## 2. Set source file (CSV) either local or remote (e.g. dropbox public folder or google spreadsheet)

	# e.g. $source_file = 'https://docs.google.com/spreadsheet/pub?key=0AuzaQN6Gty3IdFdqR3RJandpVDBaYWMzXzVnM2xHakE&single=true&gid=0&output=csv';
	# e.g. $source_file = 'https://dl.dropboxusercontent.com/u/3542031/test.csv';
	# if not specified, defaults to test.csv in assets folder
		// $sap_stats->setInputFile($source_file);

## 3. Set output style (CSS) - name of file without ".css"

	# e.g. "fancy", "bootstrap.min"
	# if not specified, defaults to "simple"
		// $sap_stats->setOutputStyle('bootstrap.min');

## ============== AVAILABLE OUTPUTS ============== ##

## Total of specified column (first column = 1, second column = 2, etc)

	# Either prints :
		// $sap_stats->printColumnTotal(2);

	# or gets :
		// $sap_stats->getColumnTotal(2);

## Formatted HTML table of CSV data

	# Either prints:
		// $sap_stats->printTable();

	# or gets :
		// $sap_stats->getTable();

## ============ OTHER PUBLIC FUNCTIONS ============ ##

## printVars : prints the currently selected style and input file (for testing)

		// $sap_stats->printVars();

define('JLV_PLUGIN_PATH', WP_PLUGIN_DIR.'/'. dirname( plugin_basename( __FILE__ ) ));
define('JLV_STYLE_PATH', JLV_PLUGIN_PATH.'/styles/');
define('JLV_ASSETS_PATH', JLV_PLUGIN_PATH.'/assets/');

Class CSVParser {

	/**
	* Set defaults
	*/

		private $input_file = 'test.csv';
		private $css_style = 'simple';

	private $the_error = '';	

	/**
	* Check for user overrides to defaults
	*/

		public function setInputFile($user_file)  
	    {  
	        $this->input_file = $user_file;
	    }  

		public function setOutputStyle($user_style) {
			$jlv_style_path = JLV_STYLE_PATH;
			if ($this->doesFileExist($jlv_style_path.$user_style.'.css', 'csv')) 
				{ 
					$this->css_style = $user_style; 
				}
			return;	
		}

	/**
	* Public functions: Ouputs formatted table / total of one column.
	* either returns value (getX) or prints value (printX)
	*/

		public function printColumnTotal($column_number) {
			//$this->getHeader();
			echo $this->readCSV($column_number);
			$this->getFooter();
		}

		public function getColumnTotal($column_number) {
			$the_total = $this->readCSV($column_number);
			return $the_total;
		}

		public function printTable() {
			$this->getHeader();
			echo $this->readCSV(0);
			//$this->getFooter();
		}

		public function getTable() {
			$the_table = $this->readCSV(0);
			return $the_table;
		}

	/**
	* Inserts style into DOM
	*/

	public function getOutputStyle() { 
		$selected_style = $this->style_path.$this->css_style.'.css';
		$verified_style = $this->doesFileExist($selected_style, 'css'); 
		$the_style = '<style type="text/css">';
		$the_style .= @file_get_contents($selected_style);  
		$the_style .= '</style>';
		return $the_style;
	}

	public function printVars() { // for testing
		echo 'Current style is: ' . $this->css_style;
		echo '<br>';
		echo 'Current file is: ' . $this->input_file;
	}

	private function getHeader() {
		echo '<html><head>';
		print_r ($this->getOutputStyle());
		echo '</head><body style="padding: 50px 100px; margin: 0px auto;"><h2>Student Advocacy Program</h2><br>';	
	}

	private function getFooter() {
		echo $this->the_error;
		echo '</body></html>';

	}

	/**
	* Loads the CSV and returns either a total or a table
	*/

	private function readCSV($passed_column_number) {
		$passed_input_file = $this->input_file;
		if ($this->checkFileType($passed_input_file) == '') {  // if it's not a URL, append the folder path
				$passed_input_file = $this->assets_path.$passed_input_file; 
			} 
		$verified_input_file = $this->doesFileExist($passed_input_file, 'csv'); // checks if csv file exists (other option "style" determines output)
		//$verified_input_file = $this->normalize($verified_input_file);
				if ($passed_column_number == 0) 
						{ 
							$processed_csv = $this->buildTable($verified_input_file); // no column specified, then output table
						} 
				else	{ 
							$column = $passed_column_number - 1; 
							$processed_csv = $this->calcTotal($verified_input_file, $column); // column specified, calc total
						} 
		return $processed_csv;		
	}

	/**
	* Checks if the specified file exists (CSV or CSS)
	*/

	private function doesFileExist($passed_input_file, $type) { 
		ini_set('auto_detect_line_endings',TRUE); // Allows for CSV files saved from Mac or Windows
		$file = fopen($passed_input_file, "r"); 

		if ( $file ) 
			{ return $file; } 
		else { 
			if ( $type == 'csv' ) { 
					die('File does not exist'); 
				} else { 
					$this->the_error = '<small style="position: absolute; bottom: 0; background: #FFC; padding: 10px; border: 1px dotted red;"><i>Error: selected style not available</i></small>'; 
				} 
			}
		ini_set('auto_detect_line_endings',FALSE); // Reset to default

		}

	/**
	* Calculates total of specified column
	*/

	private function calcTotal($passed_handle, $passed_column_number) {
		while (($data = fgetcsv($passed_handle, 1000, ",")) !== FALSE) {
			$row++; 
			$sumtotal = $sumtotal + $data[$passed_column_number]; 
		}
		fclose($passed_handle);
		return $sumtotal;
	}

	/**
	* Parses loaded CSV data and outputs in html table format
	*/

	private function buildTable($passed_handle) {

		$the_table = '<table class="table table-striped  table-hover"><thead>';
		$counter = 0;
		$row = 0;

		while (($data = fgetcsv($passed_handle, 1000, ",")) !== FALSE) {
	        $num = count($data);
	        $the_table .= '<tr>'; 
	        for ($c=0; $c < $num; $c++) {$counter++;
	        	if ($row == 0) { $the_table .= '<th>'; } 
	        	else { $the_table .= '<td>'; }
	        	$the_table .= $data[$c];
	        	if ($row == 0) { $the_table .= '</th>'; } else { $the_table .= '</td>'; }
			} 
	        if ($counter <=1 ) { $the_table .= '</tr></thead><tbody>';}
	        else { $the_table .= '</tr>'; } $row++;
			} 

		$the_table .= '</tbody></table>';

		fclose($passed_handle);

		return $the_table;
	}

	/**
	* Checks if the file is a URL (to see if the local assets path should be appended)
	*/

	private function checkFileType($the_file) {
		$file_type = substr( $the_file, 0, 4 ) === "http"; // if "file" is a URL, returns a 1
		//echo $file_type;
		return $file_type;
	}

} // End Class CSVParser
?>

simple.css

table { 
	border: 1px solid red; 
}

td {
	height: 15px;
	width: 350px;
	border: 1px dotted green;
}

Also uses bootstrap CSS.

Download Source

Leave a Reply