/ Published in: PHP
See code comments for more details.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* Simple CSV Reader So, a few ground rules: - Rows must end with a newline - Rows cannot have newlines in them - All values must be enclosed in double quotes. - Double quotes are allowed inside values. If the file is not formatted according to these rules then the world as we know it will cease to exist. Available public methods: - log(): Returns an array log if something is out of order. Have a good day. */ class CSVreader { private $log; public function __construct($filename = NULL) { if ($filename) { $this->open($filename); } } private function open($filename) { foreach($lines as $key => $values) { $values = $this->line_values($values); $line = $key + 2; if ($valueCount < $fieldCount) { $missing = $fieldCount - $valueCount; for ($x=0; $x<$missing; $x++) $values[] = '(n/a)'; $this->log_message($line, "$missing ".($missing==1?'value is':'values are')." missing"); } if ($valueCount > $fieldCount) { $tooMany = $valueCount - $fieldCount; $this->log_message($line, "There ".($tooMany==1?"is 1 value":"are $tooMany values")." too many"); } $i = 0; foreach ($values as $val) { { $this->log_message($line, "There is an empty value"); } $fieldName = $fields[$i]; if ( ! $fieldName) continue; $this->{$line}->$fields[$i] = $val; $i++; } } } { } private function line_values(&$line) { foreach ($values as &$val) { } return $values; } private function log_message($line, $message) { } } /* Example.txt: "firstname","surname" "Jane","Doe" "John","Doe" */ $csv = new CSVreader('Example.txt'); foreach ($csv as $line => $row) { echo "$line: {$row->firstname} {$row->surname}<br />\n"; }