PHP: reading config.ini to array with file()

江枫思渺然 提交于 2019-12-23 20:17:05

问题


My config file looks like this:

title = myTitle;
otherTitle = myOtherTitle;

when I read the file with file(), it creates this array

[0] => title = myTitle;
[1] => otherTitle = myOtherTitle;

and what I want the array to look like is

[title] => myTitle;
[otherTitle] => myOtherTitle;

Am I using the wrong approach her? Should i just read the entire config into a sting and explode it from there?


回答1:


You can use the parse_ini_file function. It's available in PHP 4 and 5.

If your config file looks like this:

one = 1;
five = 5;
animal = BIRD;

The function will return the following associative array:

Array
(
    [one] => 1
    [five] => 5
    [animal] => BIRD
)



回答2:


I would just loop through the file and explode each line individually. Here's a simple example, after which you'll end up with $config holding all of your data as requested.

$config = array();
$lines = file("config.ini");
foreach ($lines as $line) {
    $vals = explode('=', $line, 2);
    $config[trim($vals[0])] = trim($vals[1]);
}


来源:https://stackoverflow.com/questions/1020194/php-reading-config-ini-to-array-with-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!