ok...here goes a slightly improved version
class CSVDatabase {
var $_data=null;
var $_filename=null;
/**
* @return CSVDatabase
* @param string[optional] $file
* @desc class for manipulating CSV files
*/
function CSVDatabase ($file=null) {
if (!is_null($file)) {
$this->open($file);
}
}
/**
* @return void
* @param string $file
* @desc open specified database file
*/
function open ($file) {
$this->_data=join ('', file($file));
$this->_filename=$file;
}
/**
* @return void
* @desc save database
*/
function save () {
$fp=fopen ($this->_filename, "wb");
fwrite ($fp, $this->_data);
fclose ($fp);
}
/**
* @return void
* @param int $col
* @param mixed $value
* @desc erase particular row in databse having the specified $value in the $col umn. value can also be an array...
*/
function eraseRow ($col, $value) {
// generate PCRE (has to be slightly changed if it should discard whitespaces...
$pcre='/^';
for ($i=0; $i<$col; ++$i) {
$pcre.='[^,]*?\,';
}
if (is_array($value)) {
$pcre.='(';
for ($i=0; $i<count($value); ++$i) {
$pcre.=preg_quote($value[$i]);
if ($i<(count($value)-1)) {
$pcre.='|';
}
}
$pcre.=')';
} else {
$pcre.=preg_quote($value);
}
$pcre.='(\,.*?\r?\n|\r?\n)/sm';
// replace line
$this->_data=preg_replace($pcre, '', $this->_data);
}
/**
* @return void
* @param array $values
* @desc add row to database. expects 1D array with values
*/
function addRow ($values) {
$this->_data.=join(',', $values) . "\n";
}
/**
* @return array
* @param int $key_col
* @param mixed $key_value
* @desc get row for particular key value in 1D array
*/
function getRow ($key_col, $key_value) {
$pcre='/^(';
for ($i=0; $i<$key_col; ++$i) {
$pcre.='[^,]*?\,';
}
$pcre.=preg_quote($key_value);
$pcre.='(\,.*?\r?\n|\r?\n))/sm';
// fetch row
preg_match($pcre, $this->_data, $result);
$result=split(',', trim($result[0]));
return ($result);
}
}
// ---------
// } usage {
// ---------
//$db=new CSVDatabase('yourcsvfile.txt');
$db=new CSVDatabase();
// data needs newline at end
$db->_data='1111,entryOne,data
2222,entryTwo,data
3333,entryThree,data
4444,entryFour,data
5555,entryFive,data
6666,entrySix,data
';
$db->addRow(array(7777, 'entrySeven', 'data'));
$db->eraseRow(0, 6666);
echo $db->_data;
var_dump($db->getRow(0, 4444));
//$db->save();
have fun =D