PHP Classes

File: csvwalk.php

Recommend this page to a friend!
  Classes of Martin A. Gutbrod  >  csvwalk  >  csvwalk.php  >  Download  
File: csvwalk.php
Role: ???
Content type: text/plain
Description: class+example
Class: csvwalk
help in reading csv-files
Author: By
Last change: fixed bug in Method next_row()
Date: 19 years ago
Size: 2,922 bytes


Class file image Download
##  2002
## CLASS to walk with filter through a csv-file
## Name of fields are defined in first row.

$ccsv = new csvwalk();
if ($ccsv->open("../csvfiles/file.csv")) {   # if is's a path, take the newest file of type

 $ccsv->set_filter("Sachgebiet","^3\.");     # further filters are "and" combined

 while ($ccsv->next_row()) {
  echo "<br>".$ccsv->showfield("Sachgebiet");
  echo "<br>".$ccsv->showfield("Titel");
  echo "<br>".$ccsv->showfield("ID");
  echo "<br>".$ccsv->showfield("Beginn");
  echo "<br>".$ccsv->showfield("Ende");
  echo "<br>".$ccsv->showfield("Ort");
  echo "<br>".$ccsv->showfield("Betreuer");
  echo "<hr>";}



class csvwalk {

 var $fp;
 var $length;
 var $delimiter="";
 var $csvfile="";
 var $fields=array();
 var $filter=array();
 var $arow=array();
 var $irow=0;
 var $end=false;

 ## -- Constructor 
 function csvwalk($deli=";",$len=65536) {

 ## -- open 
 function open($path) {
  if (is_dir($path)) {
  else {
  if ($this->fp=fopen($this->csvfile,"r")) {
   return true;}
  else {
   return false;}}

 ## -- Looking for newest file of $type in $path
 function newest_file($path,$type=".*") {
  if ($handle=opendir($path)) {
   while (false!==($file=readdir($handle))) { 
    if ($file!="." && $file!=".." && ereg($type,$file) && !is_dir($path."/".$file)) {
     if ($tnew>$told) {

 ## -- Set regex filter to field for reading
 function set_filter($field,$regex) {

 ## -- check one row for filter conditions
 function check_filter(&$row) {
  foreach ($this->filter as $fld => $rex) {
   if (!ereg($rex,$row[$v])) {
    return false;}}
  return true;}

 ## -- read next valid row
 function next_row() {
  while ($adat=fgetcsv($this->fp,$this->length,$this->delimiter)) {
   if (count($adat) && $this->check_filter($adat)) {
  return !$this->end;}

 ## -- read field value of row (see example)
 function showfield($field) {
  return $this->arow[$v];}

 ## -- file-pointer to start of file; reset filter manually
 function reset() {

 ## -- finish!
 function close() {
  fclose ($this->fp);}


For more information send a message to info at phpclasses dot org.