Does PHP allow *.properties file as in Java?
PHP can natively load and parse .ini
files using parse_ini_file()
.
You can also set up constants in an include file using define()
.
If you're set on XML, look into PHP's XML functionality. The simplest solution is probably to use SimpleXML.
You can also use a PHP file containing an array to store data. Example:
config.php
<?php
return array(
'dbhost' => 'localhost',
'title' => 'My app'
);
Then in another file:
$config = require 'config.php':
echo $config['title'];
parse_ini_file
doesn't have anything to do with *.properties
files in Java environments.
I create this function, that does the exact same thing as its equivalent in Java:
function parse_properties($txtProperties) {
$result = array();
$lines = split("\n", $txtProperties);
$key = "";
$isWaitingOtherLine = false;
foreach($lines as $i=>$line) {
if(empty($line) || (!$isWaitingOtherLine && strpos($line,"#") === 0)) continue;
if(!$isWaitingOtherLine) {
$key = substr($line,0,strpos($line,'='));
$value = substr($line,strpos($line,'=') + 1, strlen($line));
} else {
$value .= $line;
}
/* Check if ends with single '\' */
if(strrpos($value,"\\") === strlen($value)-strlen("\\")) {
$value = substr($value, 0, strlen($value)-1)."\n";
$isWaitingOtherLine = true;
} else {
$isWaitingOtherLine = false;
}
$result[$key] = $value;
unset($lines[$i]);
}
return $result;
}
This function was first posted on my blog.
Well, you could perfectly put some configuration in a properties file and do the parsing yourself. But in PHP it's not the appropriate format todo so.
I would define some constants and put them in a seperate php config file (like config.php) and include this where needed.
Other options would be to actually put the configuration in a xml file and use a xml library the read it. YAML (php.net) is also a popular option for simple readable configuration.