Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

New Faq

Status
Not open for further replies.

skiflyer

Programmer
Joined
Sep 24, 2002
Messages
2,213
Location
US
I put a INI Parsing faq in the FAQ section.... looking for comments or questions, or just pointing you... :)

faq434-3634
 
And I thought I was the only one who wanted this functionality. I wrote a similar function some time ago, and one to write it back to the file. This is what I came up with:
[tt]function readIniFile($filename, $parseSections = FALSE)
{
if (!($fp = fopen($filename, "r")))
return FALSE;
$sections = array();
$section = "global";
while (!feof($fp))
{
$buffer = fgets($fp, 8192);
if (preg_match('/^ *\[([A-Za-z0-9_.-]+)\] *(;.*)?\r?\n?$/', $buffer, $matches))
{
if ($parseSections == TRUE)
{
$section = $matches[1];
$sections[$section] = array();
}
}
elseif (preg_match('/^ *([A-Za-z0-9_.-]+) *= *(["\'](.*?[^\\\\])["\']|(.+?)) *(;.*)?\r?\n?$/', $buffer, $matches))
{
$name = $matches[1];
$value = str_replace("\\", "", $matches[2]);
$value = (($value{0} == '"' || $value{0} == "'") ? substr($value, 1, -1) : $value);
$sections[$section][$name] = $value;
}
elseif (preg_match('/^ *;.*\r?\n?$/', $buffer) || preg_match('/^[\t \r\n]*$/', $buffer))
;
else
return FALSE;
}
fclose($fp);
if ($parseSections != TRUE)
$sections = $sections[$section];
return $sections;
}

function writeIniFile($filename, $array, $parseSections = FALSE)
{
if (!($fp = fopen($filename, "w")))
return FALSE;
$sections = array();
if ($parseSections == TRUE)
$sections = $array;
else
$sections = array('global' => $array);
foreach ($sections as $section => $values)
{
if ($parseSections == TRUE)
fwrite($fp, "[$section]\r\n");
foreach ($values as $name => $value)
{
fwrite($fp, "$name = \"$value\"\r\n");
}
}
fclose($fp);
return TRUE;
}[/tt]

//Daniel
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top