5

我已经创建了一个现有的 ini 文件,我想知道是否有办法更新文件的一部分,或者我是否必须每次都重写整个文件?

这是我的 config.ini 文件的示例:

[config]
    title='test'
    status=0
[positions]
    top=true
    sidebar=true
    content=true
    footer=false

说我想改变[positions] top=false. 那么我会使用 parse_ini_file 来获取所有信息,然后进行更改并使用 fwrite 重写整个文件。或者有没有办法改变那个部分?

4

3 回答 3

4

我使用了你的第一个建议:

那么我是否会使用 parse_ini_file 来获取所有信息,然后进行更改并使用 fwrite 重写整个文件

function config_set($config_file, $section, $key, $value) {
    $config_data = parse_ini_file($config_file, true);
    $config_data[$section][$key] = $value;
    $new_content = '';
    foreach ($config_data as $section => $section_content) {
        $section_content = array_map(function($value, $key) {
            return "$key=$value";
        }, array_values($section_content), array_keys($section_content));
        $section_content = implode("\n", $section_content);
        $new_content .= "[$section]\n$section_content\n";
    }
    file_put_contents($config_file, $new_content);
}
于 2016-05-03T06:36:07.143 回答
1

如果使用 PHP INI 函数,则每次都必须重写文件。

如果您编写自己的处理器,则可以(有限制地)更新到位。如果您的插入比删除长或短,则无论如何您都必须重写文件。

于 2010-08-12T23:37:49.487 回答
1

这是一个完美的例子,说明何时可以使用正则表达式替换文本字符串。查看preg_replace函数。如果你不太确定如何使用正则表达式,你可以在这里找到一个很棒的教程

只是为了澄清你需要做这样的事情:

<?php

$contents = file_get_contents("your file name");
$contents = preg_replace($pattern, $replacement, $contents);

$fh = fopen("your file name", "w");
fwrite($fh, $contents);

?>

其中 $pattern 是您要匹配的正则表达式, $replacement 是您的替换值。

于 2010-08-13T00:53:17.120 回答