How to update an ini file with php?

2020-02-01 12:31发布

I have an existing ini file that I have created and I would like to know if there was a way to update a section of the file or do I have have to rewrite the entire file each time?

Here is an example of my config.ini file:

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

Say I want to change the [positions] top=false. So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file. Or is there a way just to change that section?

标签: php file fwrite
3条回答
该账号已被封号
2楼-- · 2020-02-01 12:41

This is a perfect example of when you could use regular expressions to replace a string of text. Check out the preg_replace function. If you're not quite sure how to use regular expressions you can find a great tutorial here

Just to clarify you'll need to do something like this:

<?php

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

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

?>

Where $pattern is your regex to match and $replacement is your replacement value.

查看更多
欢心
3楼-- · 2020-02-01 12:46

I used the first suggestion of you:

So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file

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);
}
查看更多
时光不老,我们不散
4楼-- · 2020-02-01 13:05

If you use the PHP INI functions, you must rewrite the file each time.

If you write your own processor, you could (with limitations) update in place. If your insertions are longer or shorter than your deletions, you'll have to rewrite the file anyhow.

查看更多
登录 后发表回答