note 78815 added to function.parse-ini-file
| From: | goulven dot chATgmailDOTcom at osu1 dot php dot net | Date: | Mon, 29 Oct 2007 14:33:50 +0000 |
| Subject: | note 78815 added to function.parse-ini-file | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131811@lists.php.net to get a copy of this message | ||
Warning: parse_ini_files cannot cope with values containing the equal sign (=).
The following function supports sections, comments, arrays, and key-value pairs outside of any
section.
Beware that similar keys will overwrite one another (unless in different sections).
<?php
function parse_ini ( $filepath ) {
$ini = file( $filepath );
if ( count( $ini ) == 0 ) { return array(); }
$sections = array();
$values = array();
$globals = array();
$i = 0;
foreach( $ini as $line ){
$line = trim( $line );
// Comments
if ( $line == '' || $line{0} == ';' ) { continue; }
// Sections
if ( $line{0} == '[' ) {
$sections[] = substr( $line, 1, -1 );
$i++;
continue;
}
// Key-value pair
list( $key, $value ) = explode( '=', $line, 2 );
$key = trim( $key );
$value = trim( $value );
if ( $i == 0 ) {
// Array values
if ( substr( $line, -1, 2 ) == '[]' ) {
$globals[ $key ][] = $value;
} else {
$globals[ $key ] = $value;
}
} else {
// Array values
if ( substr( $line, -1, 2 ) == '[]' ) {
$values[ $i - 1 ][ $key ][] = $value;
} else {
$values[ $i - 1 ][ $key ] = $value;
}
}
}
for( $j=0; $j<$i; $j++ ) {
$result[ $sections[ $j ] ] = $values[ $j ];
}
return $result + $globals;
}
?>
Example usage:
<?php
$stores = parse_ini('stores.ini');
print_r( $stores );
?>
An example ini file:
<?php
/*
;Commented line start with ';'
global_value1 = a string value
global_value1 = another string value
; empty lines are discarded
[Section1]
key = value
; whitespace around keys and values is discarded too
otherkey=other value
otherkey=yet another value
; this key-value pair will overwrite the former.
*/
?>
----
Server IP: 217.174.196.197
Probable Submitter: 195.5.214.242
----
Manual Page -- http://www.php.net/manual/en/function.parse-ini-file.php
Edit -- https://master.php.net/note/edit/78815
Del: integrated -- https://master.php.net/note/delete/78815/integrated
Del: useless -- https://master.php.net/note/delete/78815/useless
Del: bad code -- https://master.php.net/note/delete/78815/bad+code
Del: spam -- https://master.php.net/note/delete/78815/spam
Del: non-english -- https://master.php.net/note/delete/78815/non-english
Del: in docs -- https://master.php.net/note/delete/78815/in+docs
Del: other reasons-- https://master.php.net/note/delete/78815
Reject -- https://master.php.net/note/reject/78815
Search -- https://master.php.net/manage/user-notes.php