<?
/**
* This class emulate the behavior of the
* ConfigurationSettings.AppSettings class of the .NET framework.
* With this class you can write and read a Web.config file or a
* App.config file handled in the most common applications written
* in C#, VisualBasic.NET, J# or C++.NET
*
*/
class AppSettings
{
var $CurrentDir;
var $PathSeparator;
var $XmlDocument;
var $ConfigFile;
var $ConfigFileName = "Web.config";
/**
* Constructor. Sets the working directory, the path separator,
* and the location of the config file. Then, it calls a method
* that loads the config file into a Dom Object
*
*
* @return AppSettings
*/
function AppSettings()
{
$this->CurrentDir = getcwd();
$this->PathSeparator = DIRECTORY_SEPARATOR;
$this->ConfigFile = $this->CurrentDir . $this->PathSeparator . $this->ConfigFileName;
$this->CreateOrLoadConfigFile();
}
/**
* Get the value of the element 'key'
*
* @param string $key
* @return string
*/
function Get($key)
{
$xpath = $this->XmlDocument->xpath_new_context();
$obj = $xpath->xpath_eval("//configuration/appSettings/add[@key='$key']");
if($obj->nodeset[0] != null)
return $obj->nodeset[0]->get_attribute("value");
else return;
}
/**
* Set the given name and value.
* If the file already has the element, replaces the value with the
* given value
*
* @param string $key
* @param string $value
*/
function Put($key, $value)
{
if ( $this->Get($key) == "" )
{
$xpath = $this->XmlDocument->xpath_new_context();
$obj = $xpath->xpath_eval("//configuration/appSettings");
$add = $this->XmlDocument->create_element("add");
$add->set_attribute("key", $key);
$add->set_attribute("value", $value);
$obj->nodeset[0]->append_child($add);
}
else
{
$xpath = $this->XmlDocument->xpath_new_context();
$old = $xpath->xpath_eval("//configuration/appSettings/add[@key='$key']");
$old->nodeset[0]->set_attribute("value", $value);
}
$this->XmlDocument->dump_file($this->ConfigFile, false, true);
}
/**
* This method load the config file.
* If doesn't exists, try to create it.
* The working directory must have write permissions.
*
*/
function CreateOrLoadConfigFile()
{
if(!file_exists($this->ConfigFile))
{
$this->XmlDocument = domxml_new_doc("1.0");
$root = $this->XmlDocument->add_root("configuration");
$appSettings = $this->XmlDocument->create_element("appSettings");
$root->append_child($appSettings);
$this->XmlDocument->dump_file($this->ConfigFile, false, true);
}
else
{
$this->XmlDocument = domxml_open_file($this->ConfigFile);
}
}
}
?>