In this tutorial I will provide code to store key/value pair data in a CSV file and access it. If you are familiar with WordPress then you must have used update_option(), get_option() and delete_option() to store key/value pairs, in this tutorial I will provide an implementation of these functions for PHP.
In WordPress key/value pairs are stored in MySQL but in this tutorial we will be storing them in a CSV file therefore you can use them without MySQL also.
get_option, update_option and delete_option Functions
Here is the implementation code for these functions
function update_option($name, $value)
{
if(file_exists("php-options.csv"))
{
$file = fopen("php-options.csv","r");
$exists = false;
$csv = "";
while(!feof($file))
{
$data_array = fgetcsv($file);
if($data_array[0] == $name)
{
$exists = true;
}
else
{
$csv = $csv . $data_array[0] . "," . $data_array[1] . "\n";
}
}
fclose($file);
$csv = substr($csv, 0, -2);
if($exists)
{
$csv = $csv . $name . "," . $value . "\n";
file_put_contents("php-options.csv", $csv);
}
else
{
$csv = file_get_contents("php-options.csv") . $name . "," . $value . "\n";
file_put_contents("php-options.csv", $csv);
}
}
else
{
$csv = $name . "," . $value . "\n";
file_put_contents("php-options.csv", $csv);
}
}
function get_option($name)
{
$file = fopen("php-options.csv","r");
while(!feof($file))
{
$data_array = fgetcsv($file);
if($data_array[0] == $name)
{
fclose($file);
return $data_array[1];
}
}
fclose($file);
return null;
}
function delete_option($name)
{
if(file_exists("php-options.csv"))
{
$file = fopen("php-options.csv","r");
$csv = "";
while(!feof($file))
{
$data_array = fgetcsv($file);
if($data_array[0] == $name)
{}
else
{
$csv = $csv . $data_array[0] . "," . $data_array[1] . "\n";
}
}
fclose($file);
$csv = substr($csv, 0, -2);
file_put_contents("php-options.csv", $csv);
}
}
delete_option is used to delete keys if its present in the CSV file.
update_option is used to update value of a key. If key is not present then it creates a key.
get_option is used to retrieve value of a key. It returns null if key is not found.
Code Example
Here is an example of how to call the above functions
update_option("Name", "Narayan Prusty");
echo get_option("Name");
delete_option("Name");
Leave a Reply