Rafael Sanches

August 5, 2009

reading java-style properties file in PHP

Filed under: caveats, php, programming — Tags: , , , , — mufumbo @ 4:46 am

It’s very strange that PHP only support the “parse_ini_string” as configuration function. I don’t like it at all! It has problems handling quotes, new lines, and other caveats.

The only benefit of parse_ini_string against Java Properties file is that it can handle “arrays”, but I don’t think that’s a benefit anyways. I had some trouble because I was wanting to use properties file in php for translations, since I only found buggy versions on the net I had build my own:

<?php
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 can be used to create a php properties class. It should have the same behavior as the Java properties, so it should handle ” quotes and \ for new lines.

Sorry for the bad identation, wordpress hasn’t been very nice. Let me know if it have bugs 🙂

Advertisements

Create a free website or blog at WordPress.com.

%d bloggers like this: