Ein kleiner INI-File Writer/Reader in PHP
Zwei kleine Funktionen mittels derer ein INI-File ausgelesen und beschrieben werden kann. hF!
/**
* Write data to an INI file
*
* The data array has to be like this:
*
* Array
* (
* [Section1] => Array
* (
* [key1] => val1
* [key2] => val2
* )
* [Section2] => Array
* (
* [key3] => val3
* [key4] => val4
* )
* )
*
* @param string $filePath
* @param array $data
*/
function ini_write($filePath, array $data)
{
$output = '';
foreach ($data as $section => $values)
{
//values must be an array
if (!is_array($values)) {
continue;
}
//add section
$output .= "[$section]rn";
//add key/value pairs
foreach ($values as $key => $val) {
$output .= "$key=$valrn";
}
$output .= "rn";
}
//write data to file
file_put_contents($filePath, trim($output));
}
/**
* Read and parse data from an INI file
*
* The data is returned as follows:
*
* Array
* (
* [Section1] => Array
* (
* [key1] => val1
* [key2] => val2
* )
* [Section2] => Array
* (
* [key3] => val3
* [key4] => val4
* )
* )
*
* @param string $filePath
* @return array|false
*/
function ini_read($filePath)
{
if (!file_exists($filePath)) {
return false;
}
//read INI file linewise
$lines = array_map('trim', file($filePath));
$data = array();
$currentSection = null;
foreach ($lines as $line)
{
if (substr($line, 0, 1) == '[') {
$currentSection = substr($line, 1, -1);
$data[$currentSection] = array();
}
else
{
//skip line feeds in INI file
if (empty($line)) {
continue;
}
//if no $currentsection is still null,
//there was missing a "[<sectionName>]"
//before the first key/value pair
if (null === $currentSection) {
return false;
}
//get key and value
list($key, $val) = explode('=', $line);
$data[$currentSection][$key] = $val;
}
}
return $data;
}
Ähnliche Artikel
- Statische Methoden sind einfach nur Funktionen - also Vorsicht!
- Properties: Neue Get-/Set-Syntax für PHP?
- PHP zvals und Referenzen erklärt




