-
-
Save subhashdasyam/8ea003a58ffe9e512f96a11b380ff898 to your computer and use it in GitHub Desktop.
Read Write CSV with SPL functions PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
(PHP_SAPI !== 'cli' || isset($_SERVER['HTTP_USER_AGENT'])) && die('cli only'); | |
class RW_SPL{ | |
public function __construct() { | |
$this->filename = './item.db'; | |
$this->rows = array("item"=>0,"type"=>1,"price"=>2,"age"=>3,"location"=>4); | |
} | |
private function _read(){ | |
file_exists($this->filename) or die("File doesn't exist\r\n"); | |
$file = new SplFileObject($this->filename); | |
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE); | |
$file->setCsvControl(',', '"', '\\'); // this is the default anyway though | |
return $file; | |
} | |
public function _add($args){ | |
array_shift($args); | |
$file = fopen($this->filename,"a+"); | |
fputcsv($file,$args); | |
fclose($file); | |
} | |
public function search($args){ | |
$res = array(); | |
list($action,$search_type,$search_value) = $args; | |
foreach($this->_read() as $row){ | |
if($row[$this->rows[$search_type]] == $search_value){ | |
array_push($res, $row); | |
} | |
} | |
return $res; | |
} | |
} | |
echo "Command:\n"; | |
echo " Add an item\n"; | |
echo " add <item> <sale/rent> <price_usd> <location> <age>\n"; | |
echo " Search by item/location/age/price \n"; | |
echo " search <type> <value>\n"; | |
echo " q\n"; | |
echo " Quit\n"; | |
$cmd = array(); | |
$stdin = fopen("php://stdin", "r"); | |
$rw = new RW_SPL(); | |
while (!feof($stdin)) { | |
echo " >> "; | |
$input = fgets($stdin); | |
$cmd = explode(" ", trim($input)); | |
$cmd[0] = strtolower($cmd[0]); | |
switch ($cmd[0]) { | |
case "add": | |
if (count($cmd) != 6) { | |
echo "Wrong number of parameters.\n add <item> <sale/rent> <price> <location> <age> \n"; | |
continue; | |
} | |
$rw->_add($cmd); | |
break; | |
case "search": | |
if (count($cmd) != 3) { | |
echo "Wrong number of argments for search.\n search <type> <value>\n"; | |
continue; | |
} | |
foreach($rw->search($cmd) as $row) | |
print implode(' ',$row)."\r\n"; | |
break; | |
case "q": | |
exit(0); | |
break; | |
default: | |
echo "This version only supports add,search commands.\n"; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment