How to read write data in properties file using php

For reading and writing data into properties file I am using parse_ini_file() function in this post.
Create a file name with extension .properties like I have created below:


Reading Data: below code read data from above file using key:
function getValue($key)
{
    $ini_array = parse_ini_file("File.properties");
    $value =  $ini_array[$key];
    return $value;
}
getValue(“Name”);
getValue(“URL”);


If you run above file you will get Name and Url values.

Writing Data: below code write data into mentioned file if key is already exist then it update value and if key not exist it add new key value. Also if file not exist then it create new file.
function writeValue($key, $value)
{                                                               
    $filename= "File.properties";
    $ini_array = parse_ini_file($filename);
    $values =  $ini_array[$key]; 
    $datareading = fopen($filename, 'r');
    $content = fread($datareading,filesize($filename));
    fclose($datareading);
    $content = str_replace($values, $value, $content);
    $fileWrite = fopen($filename, 'w');
    fwrite($fileWrite,$content);
    fclose($fileWrite);                       
}
writeValue("Name", "Roadtoautomation");
writeValue("URL", " http://www.roadtoautomation.blogspot.com ");
writeValue("NewName", "Roadtoautomation");


When you run you will see that values are updated and new key values added for the “NewName” key



1 comment:

Leave your comments, queries, suggestion I will try to provide solution