【问题标题】:How to update an ini file with php?如何使用 php 更新 ini 文件?
【发布时间】:2011-03-29 05:17:51
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: php file fwrite


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      <?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 是您的替换值。

      【讨论】:

        【解决方案3】:

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

        那么我会使用 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);
        }
        

        【讨论】:

        • 对我很有魅力..干杯!
        • 如果您的值可能包含特殊字符,例如 = 或 \n,请使用 return "$key='$value'";
        猜你喜欢
        • 1970-01-01
        • 2016-06-05
        • 2011-08-04
        • 2012-10-04
        • 1970-01-01
        • 2015-10-13
        • 2013-04-05
        • 2011-08-07
        相关资源
        最近更新 更多