STAY INFORMED
following content serves as a personal note and may lack complete accuracy or
certainty.
Minimal-Mistakes instruction
Useful vscode Shortcut Keys
Unix Commands
npm Commands
Vim Commands
Git Note
Useful Figma Shortcut Keys
PHP_5(handling CSV)
CSV(Comma-Separated Values) file is plain text file format commonly used for storing and exchanging tabular data.
define config files
You can define constants in your config file. Once you defined, you cannot redefine it and you can use the values in your program
// config.inc.php
<?php
// constant variable, file path
define("CSV_FILE", "./data/people.csv");
define("ERROR_LOG", "./log/error_log");
?>
create csv parser class
CSV parser is a tool that reads and interprets CSV-formatted data.
<?php
class CSVParser{
public static function parsePeople($csvData) : array {
$allPeople = array(); // create empty 2d array
$lines = explode("\n",$csvData); // explode each row(one perseon)
for ($i = 1; $i < count($lines); $i++){
$cols = explode(",", $lines[$i]); // explode each column(one object of person data)
try{
if (count($cols) != 3){
throw new Exception("Error parsing" . CSV_FILE . " on line $i");
}
else{
$p = new Person();
// add person's data to array for appending csv file
$p->setFirstName(htmlentities(trim($cols[0])));
$p->setLastName(htmlentities(trim($cols[1])));
$p->setEmail(htmlentities(trim($cols[2])));
$allPeople[] = $p;
}
}
catch(Exception $pe){
}
}
return $allPeople;
}
}
?>
create file agent class
This class will be used for handling csv file. Here is an example of appending person’s data.
<?php
class FileAgent{
public static function appendCSVFile(string $contents){
try{
$fh = fopen(CSV_FILE, "a");
if (!$fh){
throw new Exception("Cannot open " . CSV_FILE . "for writing");
}
fwrite($fh, $contents);
fclose($fh);
}
catch(Exception $fe){
echo $fe->getMessage();
error_log($fe->getMessage(), 3, ERROR_LOG);
}
}
public static function readFile() : string{
try{
$fh = fopen(CSV_FILE, 'r');
$fileContents = fread($fh, filesize(CSV_FILE));
fclose($fh);
}
catch(Exception $fe){
echo $fe->getMessage();
error_log($fe->getMessage(), 3, ERROR_LOG);
}
return $fileContents;
}
}