PHP Function: config_load()

A very basic configuration file (ini style) parser for PHP 4 & 5.
It is all easily saved to a variable.

function config_load($filename, $default = 'core') {
$var_prefix = $default;
if (!file_exists($filename)) return false;
$config = file($filename);
$config_arr = Array();
foreach ($config as $config_item) {
$config_item = trim($config_item);
if (substr($config_item,0,1) == '#'||substr($config_item,0,1) == "*") {
continue;
} elseif (substr($config_item,0,1)=='['&&substr($config_item,-1)==']') {
$var_prefix = substr($config_item, 1, strlen($config_item)-2);
} elseif (strpos($config_item,'=') && $config_arr = explode('=', $config_item)) {
$config_key = trim($config_arr[0]);
$config_val = trim($config_arr[1]);
$config_arr[$var_prefix][$config_key] = $config_val;
}
} return $config_arr;
}

An example config.ini:

# You can include comments in your config.ini too
[page]
title		= An example page title
theme		= demo
description = PHP Configuration parser function
keywords	= simple, php4, config, parser, function, arkinex
 
[dates]
news	 = jS M Y
latest	 = j M
comments = jS M Y
match	 = jS M Y
results	 = jS M
forums	 = jS M Y
downloads= jS M Y

An example usage:

$config = config_load('config.ini');
// To display: An example page title.
echo $config['page']['title'];
// To display the entire configuration (for debug?)
echo '<code>';
print_r($config);
echo '</code>';

Once again, any feedback or suggestions, please reply to this post.

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

Looks nice, but it doesnt work for me. this is all it shows “Array ( [0] => downloads [1] => jS M Y [dates] => Array ( [downloads] => jS M Y ) )” it doesnt even show the whole config.ini in the array

Aw, i’m sorry for this, I just tested the function and your right.
From now on, i’m going to test them all before i put them on…
The reason for this breaking is, the original was in a class, let me rewrite this.

Thanks for the post.

Leave a comment

(required)

(required)