2010-08-12 63 views
3

我有一個現有的ini文件,我已經創建,我想知道是否有方法來更新文件的一部分或我必須每次重寫整個文件?如何使用php更新ini文件?

這裏是我的config.ini文件的例子:

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

說我想改變[positions] top=false。所以我會使用parse_ini_file來獲取所有信息,然後進行更改並使用fwrite來重寫整個文件。或者有沒有辦法改變這一部分?

回答

1

如果您使用PHP INI函數,則必須每次重寫該文件。

如果你編寫你自己的處理器,你可以(有限制)更新。如果你的插入比你的刪除更長或更短,你將不得不重寫文件。

1

這是您可以使用正則表達式替換文本字符串的完美示例。檢查preg_replace函數。如果你不太清楚如何使用正則表達式,你可以找到一個偉大的教程here

只是爲了澄清你需要做這樣的事情:

<?php 

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

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

?> 

其中$模式是你的正則表達式匹配和$替換是您的替換值。

3

我用你的第一個建議:

所以我會使用parse_ini_file把所有的infromation的然後讓我的變化,並使用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); 
} 
+0

爲我工作的魅力..乾杯! – irishwill200 2017-06-14 14:30:10