HomePHP Page 4 - Configuration Manipulation With PHP Config
Different Strokes - PHP
Tired of writing (and rewriting) code to manage your application's configuration variables? Take a look at the PEAR Config class, a PHP toolkit designed specifically for manipulating configuration files and the data within them. This article demonstrates using the Config class to read and write configuration files in XML, PHP and INI formats, and use built-in methods to easily build Web-based application configuration modules.
I noted, on the previous page, that altering the second argument to writeConfig() significantly affects the format of the configuration file. Let's look at that a little more closely, by trying out the different variants. Consider the following rewrite of the previous example, which writes the configuration data as a generic configuration file instead of a PHP structure:
As with the PHPArray type, you can customize the output format by specifying the characters to be used for comments, delimiters and line endings. So, for example, if you wanted the variable-value pairs separated by commas, you could use this script,
And finally, you can even write configuration data using the XML standard, with the XML type (note that this requires the presence of two other XML classes from PEAR, the Parser class and the Util class in order to work). Here's the script,
If you know a little bit about XML, you'll know that is not really well-formed XML, since the root element is missing. This can be easily rectified; just add an option specifying the name of this root element to the writeConfig(), as done earlier with the PHPArray type. Here's the revised script,