Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

parsing - php parse_ini_file oop & deep

I would like to make use of somehting like [parse_ini_file][1].

Lets say for instance I have a boot.ini file that I will load for further procedure:

    ;database connection settings
[database]
type        =   mysql;
host        =   localhost;
username    =   root;
password    =   "";
dbName      =   wit;

However, I would like to have it in a different way as the php array would be:

$ini['database']['whatever']

So first of all I would like to have my boot.ini like this structure:

;database settings (comment same style)
db.host1.type = mysql;
db.host1.host = localhost;
db.host1.username = root;
db.host1.password = "";
db.host1.dbName = wit;

db.host2.type = mysql;
db.host2.host = otherHost;
db.host2.username = root;
db.host2.password = "";
db.host2.dbName = wit;

So when I now access the file I would like to access it this way:

$ini['db']['host1']['whatever']

And on top of that I would like to do it via OOP so lets say: $ini->db->host1->whatever

or `$ini->db->host1` 

will return an array with all the attributes such as type, host, username, password and the dbName;

I appreciate anykind of help. Thank you very much in advance.

  [1]: http://uk2.php.net/manual/en/function.parse-ini-file.php
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, you need to postprocess the parse_ini_file result array then.

$ini_array = parse_ini_file("bootstrap.ini");

$ini = new stdclass;
foreach ($ini_array as $key=>$value) {
    $c = $ini;
    foreach (explode(".", $key) as $key) {
        if (!isset($c->$key)) {
            $c->$key = new stdclass;
        }
        $prev = $c;
        $c = $c->$key;
    }
    $prev->$key = $value;
}

Update Hackety-Hack. Now using an extra $prev to unset the last object level again. (A for loop to detect the last $key would have worked better).

If you want to use the array syntax and the object syntax, then replace the new stdclass with new ArrayObject(array(), 2);.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...