path . $table . '.txt'; $fp = fopen($filename, "r"); if(!$fp) { $this->error("Cannot open CSV file $filename for read"); return FALSE; } /* field names are in first line of file */ $fields = fgetcsv($fp, CSV_BUFSIZ); $numfields = count($fields); if(!(is_array($fields) && count($fields) > 0)) { $this->error("No field names found in CSV file $filename"); fclose($fp); return FALSE; } /* data follows */ $result = array(); while(!feof($fp)) { $data = fgetcsv($fp, CSV_BUFSIZ); /* ignore blank lines, e.g. the last one */ if (is_array($data) && count($data) > 0) { $row = array(); $numdata = count($data); for($i = 0; $i < $numfields; $i++) { $row[$fields[$i]] = isset($data[$i]) ? $data[$i] : ""; } $result[] = $row; } } fclose($fp); return $result; } /* public: write a comma separated variable file named $table.txt * with the data from $data. The file must already exist and * contain the field names. */ function write($table, $data) { $filename = $this->path . $table . '.txt'; /* read field names from the first line of the file */ $fp = fopen($filename, "r"); if(!$fp) { $this->error("Cannot open CSV file $filename for read"); return FALSE; } $fields = fgetcsv($fp, CSV_BUFSIZ); if(!(is_array($fields) && count($fields) > 0)) { $this->error("No field names found in CSV file $filename"); fclose($fp); return FALSE; } fclose($fp); /* open file for writing */ $fp = fopen($filename, "w+"); if(!$fp) { $this->error("Cannot open CSV file $filename for write"); return FALSE; } /* write the field names */ $str = ""; reset($fields); while( list($key, $field) = each($fields)) { $str = $str . "\"$field\", "; } $str = substr($str, 0, -2) . $this->nl; fputs($fp, $str); /* write the data */ reset($data); while( list($key, $row) = each($data)) { $str = ""; reset($fields); while( list($key, $field) = each($fields)) { $str = $str . "\"$row[$field]\", "; } $str = substr($str, 0, -2) . $this->nl; fputs($fp, $str); } fclose($fp); return TRUE; } /* private: handle errors */ function error($msg) { echo "

Error: " . $msg . "

" . $this->nl; } } /* end of class Csv */ ?>