<?
/**
* 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 = new DOMXPath($this->XmlDocument);
$obj = $xpath->query("/configuration/appSettings/add[@key='$key']");
if($obj->item(0) != null)
return $obj->item(0)->getAttribute("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 = new DOMXPath($this->XmlDocument);
$obj = $xpath->query("/configuration/appSettings");
$add = $this->XmlDocument->createElement("add");
$add->setAttribute("key", $key);
$add->setAttribute("value", $value);
$obj->item(0)->appendChild($add);
}
else
{
$xpath = new DOMXPath($this->XmlDocument);
$old = $xpath->query("/configuration/appSettings/add[@key='$key']");
$old->item(0)->setAttribute("value", $value);
}
$this->XmlDocument->save($this->ConfigFile);
}
/**
* 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 = new DOMDocument("1.0", "UTF-8");
$root = $this->XmlDocument->createElement("configuration");
$appSettings = $this->XmlDocument->createElement("appSettings");
$root->appendChild($appSettings);
$this->XmlDocument->appendChild($root);
$this->XmlDocument->save($this->ConfigFile);
}
else
{
$this->XmlDocument = new DOMDocument("1.0", "UTF-8");
$this->XmlDocument->Load($this->ConfigFile);
}
//die(htmlentities($this->XmlDocument->saveXML()));
}
}
?>