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

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");
$contents = 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.

于 2010-08-13T00:53:17.120 に答える
1

PHP INI 関数を使用する場合は、毎回ファイルを書き直す必要があります。

独自のプロセッサを作成する場合は、(制限付きで) その場で更新できます。挿入が削除よりも長いか短い場合は、とにかくファイルを書き直す必要があります。

于 2010-08-12T23:37:49.487 に答える