PHP:使用 file() 将 config.ini 读取到数组

发布于 2024-07-25 20:26:37 字数 361 浏览 2 评论 0原文

我的配置文件如下所示:

title = myTitle;
otherTitle = myOtherTitle;

当我使用 file() 读取文件时,它会创建这个数组

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

,而我希望数组看起来像

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

我是否使用了错误的方法? 我应该将整个配置读入一个刺中并从那里爆炸吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤者何惧 2024-08-01 20:26:37

您可以使用 parse_ini_file 函数。 它在 PHP 4 和 5 中可用。

如果您的配置文件如下所示:

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

该函数将返回以下关联数组:

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

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
)
君勿笑 2024-08-01 20:26:37

我只是循环遍历文件并单独分解每一行。 这是一个简单的示例,之后您将得到 $config 根据请求保存所有数据。

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

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]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文